Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable input some symbols to JTextField

Tags:

java

swing

How can I disable input of any symbol except digits to JTextField?

like image 881
maks Avatar asked Feb 01 '11 14:02

maks


People also ask

How do I disable JTextField?

To disable JtextField/JTextArea, call the method setEnabled() and pass the value “false” as parameter. JTextField textField = new JTextField(); textField.

How do I allow only numbers in JTextField?

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(''); }; });

What happens if you press Enter in JTextField?

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.


1 Answers

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
      }
   }
});
like image 176
gorlok Avatar answered Oct 12 '22 01:10

gorlok