我正在尝试控制Add Employee类中的按钮,因此如果接受用户输入或不使用 InputVerifier ,我可以禁用或启用它。我做了什么我为 addEmployeeButton
做了一个getter和setterpublic class AddEmployee extends javax.swing.JInternalFrame{
public JButton getJButton()
{
return addEmployeeButton;
}
public void setJButton(JButton buttonObject)
{
buttonObject = addEmployeeButton;
}
private void registerJComponents()
{
//INPUT VERIFIER
tfLastName.setInputVerifier(new ValidateComponents(addEmployeeButton));
tfFirstName.setInputVerifier(new ValidateComponents(addEmployeeButton));
tfMiddleName.setInputVerifier(new ValidateComponents(addEmployeeButton));
tfNickname.setInputVerifier(new ValidateComponents(addEmployeeButton));
taAddress.setInputVerifier(new ValidateComponents(addEmployeeButton));
tfContact.setInputVerifier(new ValidateComponents(addEmployeeButton));
tfContactName.setInputVerifier(new ValidateComponents(addEmployeeButton));
tfContactNo.setInputVerifier(new ValidateComponents(addEmployeeButton));
}
}
我正从另一个名为ValidateComponents的类访问它。但是disable
方法期望传递AddEmployee实例。我不能给出null
的值,因为这会给我一个NullPointerException。
public class ValidateComponents extends InputVerifier
{
JButton myButton;
public ValidateComponents(JButton button)
{
this.myButton = button;
}
public void disable(JButton name, boolean disable, AddEmployee employee)
{
employee.setJButton(name);
name.setEnabled(!disable);
}
@Override
public boolean verify(JComponent input)
{
String tf = null;
//String ta = null;
String name = input.getName(); //GETTING THE NAME OF THE COMPONENT
if(input instanceof JTextField)
{
tf = ((JTextField) input).getText();
if(name.equals("tfLastName") || name.equals("tfFirstName") || name.equals("tfMiddleName") || name.equals("tfNickname") || name.equals("tfGuardianContactName"))
{
boolean valid = tf.trim().length() > 0;
disable(myButton, !valid);//Button instance
if(!valid)
{
input.setBackground(Color.PINK);//Set background color to pink if false.
input.setToolTipText("Fields cannot left blank");
return false;//Return false if the component need to keep focus
}
else
{
}
}
}
input.setBackground(Color.WHITE);//Set backgroud color to white if true.
return true;//Return true if the component should give up focus
}
}
第二次尝试:
当我尝试在方法外创建AddEmployee类的实例时。它给了我一个 StackOverFlowError ,这指向我创建的对象。有人能告诉我解决这个问题的最佳方法是什么?任何帮助都会非常感激。
private AddEmployee employee = new AddEmployee();