0

I'm trying to add validation to 4 JTextFields using only numeric characters (0-9). The code I have for one JTextField is:

txtf_xCoord.addKeyListener(new KeyAdapter()
    {
        @Override
        public void keyTyped(KeyEvent keyEvent)
        {
            if (txtf_xCoord.getText().length() < 3 && keyEvent.getKeyChar() >= '0' && keyEvent.getKeyChar() <= '9')
            {
                // Optional
                super.keyTyped(keyEvent);
            }
            else
            {
                // Discard the event
                keyEvent.consume();
            }
        }
    });

Is there a more efficient way of adding this validation to the rest of the JTextFields without copy and pasting the code for each?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
drizzy
  • 139
  • 2
  • 15
  • make a class that extends from JTextField and in it add your listener. and everywhere of your program create of that class. – mehdi Mar 07 '12 at 13:19
  • 1
    @medhi - wrong ... you _never_ use a KeyListener in Swing, especially not for validating text input – kleopatra Mar 07 '12 at 14:45

3 Answers3

3

You can use an InputVerifier, take a look at the following code :

public class NumericVerifier extends InputVerifier {
        @Override   
    public boolean verify(JComponent input) {
            //Check type of the control
                String text = "";

if(input instanceof JTextField) {   
                JTextField tf = (JTextField) input; 
                text = tf.getText().trim(); 
            }

        boolean matches = text.matches("^\\d+$");
        input.setBackground( ( matches ) ? Color.WHITE :  Color.RED);
        return matches; 
    }   
}
aleroot
  • 71,077
  • 30
  • 176
  • 213
2
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

Well you can convert your anonymous class to a real class and then instantiate that class everywhere. Now, you could also take a look at JFormattedTextField

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117