How can I disable input of any symbol except digits to JTextField
?
To disable JtextField/JTextArea, call the method setEnabled() and pass the value “false” as parameter. JTextField textField = new JTextField(); textField.
txtAnswer. addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int key = e. getKeyCode(); /* Restrict input to only integers */ if (key < 96 && key > 105) e. setKeyChar(''); }; });
Now the event is fired when the Enter key is used. Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button. JButton button = new JButton("Do Something"); button.
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
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With