2

How to prevent user from entering certain charcters in 'JTextField' and if enters that character is entered ,do not show it in the textfield

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2076400
  • 27
  • 1
  • 4
  • not this is about DocumentFilter, KeyListener is proper only in the case that there is key shortcut with three or more keys pressed in the same time, – mKorbel Mar 29 '13 at 14:40

2 Answers2

7

You can either use a JFormattedTextField or create a custom DocumentFilter.

camickr
  • 321,443
  • 19
  • 166
  • 288
-2
JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
  char c = e.getKeyChar();
  if (//Write your condition here) {
     e.consume();  // ignore event
}});

More on the same here

Community
  • 1
  • 1
Anuj Balan
  • 7,629
  • 23
  • 58
  • 92