javaif-statementdialogintmessagedialog

Java client/server validation: if jtextfield empty?


For a textfield that is empty using client side validation with message dialog pop up boxes how do you code it for integer and double?

I implemented the String empname however I can't seem to make a dialog box pop up for empid and payrate, any suggestions would be greatly appreciated.

String empname = jtfEname.getText();
    //If no text is entered display pop up dialog box.
if(empname.length()==0)
    JOptionPane.showMessageDialog(null, "Please Enter Your Name");

int empid = Integer.parseInt(jtfEid.getText().trim());
    //If no id is entered display pop up dialog box.
if (empid.equals(""))
    JOptionPane.showMessageDialog(null, "Please Enter Your Id");

double payrate = Double.parseDouble(jtfPayRate.getText().trim());
    //If no payrate is entered display pop up dialog box
if (payrate.equals(""))
    JOptionPane.showMessageDialog(null, "Please Enter Your Pay Rate");

Solution

  • Try

    int empid; 
    try {
        empid = Integer.parseInt(jtfEid.getText().trim());
    } catch(NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Please Enter Your Id");
    }
    

    If the user enters anything but int, this should open up the Dialog box. Same thing goes for the payrate.

    double payrate;
    try {
        payrate = Double.parseDouble(jtfPayRate.getText().trim());
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Please Enter Your Pay Rate");
    }