Francisunoxx Francisunoxx - 2 months ago 19
Java Question

Validating InputVerifier from GUI Builder

I created some

JTextFields
and
JComboBox
using Gui Builder(Drag and drop) and added a submit trigger
JButton
. I wanted to validate the Swing Controls by checking if textfields are empty calling the method
verify()
in my GUI.

validation class

public class validation extends InputVerifier
{
@Override
public boolean verify(JComponent input)
{
String text = null;
String cb = null;

if(input instanceof JTextField)
{
text = ((JTextField) input).getText();
}
else if(input instanceof JComboBox)
{
cb = ((JComboBox) input).getSelectedItem().toString();
}

return true;
}
}


AddEmployee

I already created a instance of my class validation.

public class AddEmployee extends javax.swing.JInternalFrame{

/**
* Creates new form AddEmployee
*/
validation v = new validation();

private void addButtonActionPerformed(java.awt.event.ActionEvent evt){
String lastName = tfLastName.getText();
String firstName = tfFirstName.getText();

tfLastName.setName("lastName");
tfFirstName.setName("firstName");

v.verify(tfLastName,tfFirstName);
}

}//end of AddEmployee


When I'm trying to passed the variable names of my
JTextFields
in
verify()
method it throws me a error.


no suitable method found for verify(JTextFields,JTextFields) method InputVerifier.verify is not applicable


What I did I created a void method
verify()
under validation class.

public void verify(JTextField tfLastName, JTextField tfFirstName) {

}


Question


  • Where should I validate textfields? Should I validate under AddEmployee or validation class?



Any help or tips I would greatly appreciated!

Answer

Best practice: when you create the JTextField assign the verifier to it:

  tfLastName.setInputVerifier(new validation());

BTW: Use correct java naming convention: Validation

Comments