Search code examples
javaswingjframejtextfield

How can I reset JTextField.......?


I used the below pgm to save the details on address book. I want to check the mob filed whether it is an int or not. It will execute properly at the first time (If i enter letter in mob field it will not save). but from the 2nd time on words it will save even if i entered a letter in the mob filed. mob will store the previous value. How can i clear the mob filed after executing the first time.....

 public void savePerson() {  
    name   =   jtfName.getText();
    name   =   name.toUpperCase();  
    jtfName.setText(name);
    address = jtfAddress.getText();

    try {
        landline = Integer.parseInt(""+jtfLandline.getText());
    } catch(Exception e) {          
    }

    try {           
       mob = Integer.parseInt(""+jtfmob.getText());     
    }catch(Exception e) {
    }

    email   = jtfEmail.getText();
   if(name.equals("")) {
        JOptionPane.showMessageDialog(null, "Please enter person name.");           
   } else if(mob == 0) {
        JOptionPane.showMessageDialog(null, "Please enter Mobile Number.");
   } else {
          //create a PersonInfo object and pass it to PersonDAO to save it
          PersonInfo person = new PersonInfo(name, address, landline, mob , email);
          pDAO.savePerson(person);
          JOptionPane.showMessageDialog(null, "Person Saved");            
          clear();         
   }
 }

Solution

  • Try out this,

    Once the first iteration is over, reset your text field by setting like below

    jtfmob.setText("");
    

    To get the number inputs alone, try the following codes

    jtfmob = new JFormattedTextField(NumberFormat.getInstance());