How to prevent user from entering certain charcters in 'JTextField' and if enters that character is entered ,do not show it in the textfield
Asked
Active
Viewed 5,636 times
2
-
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 Answers
7
You can either use a JFormattedTextField or create a custom DocumentFilter.

camickr
- 321,443
- 19
- 166
- 288
-
Implementation example: https://www.rgagnon.com/javadetails/java-0197.html – PAX Jul 20 '21 at 06:07
-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
-
6-1, You should NOT be using a KeyListener. Swing has newer and better API's for this problem. For example try pasting text into your text field and see what happens. – camickr Mar 29 '13 at 15:34
-
1