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?