0

ok, so as the title tells you, that i need to validate the 12 textboxes on ONE tab. i was thinking to do it by opening every text box individually and add the validation code. But the problem is that it may not show the error until the Ok or any other key is pressed. i am working with JDBC and need to validate the textboxes before entering into the database. Any help would be greatly appreciated! Like ID, date, email, phone, address.

Samar Qureshi
  • 23
  • 1
  • 8
  • See also [*Validating Input*](http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#inputVerification). – trashgod Jan 19 '15 at 12:14
  • You can use a `JFormattedTextField` to perform validation, as shown [here](http://stackoverflow.com/a/13424140/1076463) – Robin Jan 19 '15 at 14:19

1 Answers1

0

Here is a way to do this

public class Test extends JFrame {
  JTextField text = new JTextField("Press Return", 40);

  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    text.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) { // Called whenever any action preform on textfield
        System.out.println("Text=" + text.getText());
        // Do validation here 
      }
    });

    getContentPane().add(text, "Center");
    pack();
  }

  public static void main(String[] args) {
    new Test().setVisible(true);
  }
}
Junaid
  • 2,572
  • 6
  • 41
  • 77
  • ok, not to sound dumb.. but you wrote do validation here.. can i do validation of all text boxes here? like i f i need to make sure the data entered is only INT.. what will i have to do? – Samar Qureshi Jan 19 '15 at 07:42
  • or making a separate class is better? – Samar Qureshi Jan 19 '15 at 07:44
  • If you want to validate `int` the just convert `string` to `int`, if get no `Exception` then validate `true` else `false`. And what do you mean by separate classes ? What classes ? Its totally depend upon your logic. – Junaid Jan 19 '15 at 07:51
  • like i can make a validate class and make methods in it and call the methods in the text fields to see if its validated. and yes i have done the conversion. think i should just ad the validate step – Samar Qureshi Jan 19 '15 at 07:55
  • Yeah that would be better. In my answer I just give you an idea. So all you need is call the validator's class method from `listener` (under my comment `// Do validation here `). – Junaid Jan 19 '15 at 07:59
  • oh awesome! so i can validate all the text fields in one class and call the class there? that sounds easy. – Samar Qureshi Jan 19 '15 at 08:10