Hello,
I have a textfield with an input verifier and a button. Does anyone know how you can prevent button actions when the input in the textfield is invalid?
Here's an example. If you enter a number and hit the button, then everything is okay. If you enter characters and hit the button, then the action of the button shouldn't be performed. The button obviously has getVerifyInputWhenFocusTarget() set to true, but it still executes its action after a mousepress, even though the verifier of the textfield tells it not to do that.
Thank you very much! :)
package testing.misc;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
public class InputTest extends javax.swing.JFrame {
private javax.swing.JButton myButton;
private javax.swing.JTextField myTextField;
public InputTest() {
initComponents();
}
private void initComponents() {
// create components
myTextField = new javax.swing.JTextField();
myButton = new javax.swing.JButton();
setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout( new java.awt.FlowLayout());
myTextField.setHorizontalAlignment( javax.swing.JTextField.RIGHT);
myTextField.setText( "1");
myTextField.setPreferredSize( new java.awt.Dimension( 120, 20));
getContentPane().add( myTextField);
// button action
myButton.setText( "Hit Me");
myButton.addActionListener( new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
myButtonActionPerformed( evt);
}
});
getContentPane().add( myButton);
// check to what getVerifyInputWhenFocusTarget is set
System.out.println( "myButton.getVerifyInputWhenFocusTarget: " + myButton.getVerifyInputWhenFocusTarget());
// create input verifier: only numbers are allowed
InputVerifier myVerifier = new InputVerifier() {
@Override
public boolean verify(JComponent input) {
try {
Integer.parseInt( myTextField.getText());
} catch( Exception ex) {
System.out.println( "error");
return false;
}
System.out.println( "ok: " + myTextField.getText());
return true;
}
};
myTextField.setInputVerifier( myVerifier);
pack();
}
private void myButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println( "Button pressed.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater( new Runnable() {
public void run() {
new InputTest().setVisible( true);
}
});
}
}