How can I disable input of any symbol except digits to JTextField
?
For a better user experience
Others have mentioned the use of JFormattedTextField or KeyListeners to prevent invalid data from being entered but from a usability point of view I find it very annoying to start typing into a field and nothing happens.
To provide a better user experience you can allow the user to enter non-numeric values in the field but use a validator to provide feedback to the user and disable the submit button.
You can add a custom KeyListener
that intercepts key strokes and doesn't propogate invalid key strokes to the JTextField
.
How to Use Formatted Text Fields
amountField = new JFormattedTextField(NumberFormat.getIntegerInstance());
You can also create your own format to customize.
The answer is JFormattedTextField
. See my answer on this duplicate question:
You can use a JFormattedTextField. Construct it using a NumberFormatter and it will only accept numbers.
The
JFormattedTextField
has a bunch of configurable options that let you decide how bad input is handled. I recommend looking at the documentation.
Just consume all chars that is not a digit like this:
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.add(new JTextField() {{
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (!Character.isDigit(e.getKeyChar()))
e.consume();
}
});
}});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
Option 1) change your JTextField with a JFormattedTextField, like this:
try {
MaskFormatter mascara = new MaskFormatter("##.##");
JFormattedTextField textField = new JFormattedTextField(mascara);
textField.setValue(new Float("12.34"));
} catch (Exception e) {
...
}
Option 2) capture user's input from keyboard, like this:
JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ( ((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
e.consume(); // ignore event
}
}
});