Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTextField Keylistener can't erase input

I have a JTextField that works perfectly fine when someone enters a number instead of a letter. My only problem is that that the number then does not dissappear. The user can't enter any other numbers but that last number pressed stays always in the filed! Why?

    searchF.addKeyListener(new KeyAdapter(){
            public void keyTyped(KeyEvent e){
                char ch = e.getKeyChar();
                if(Character.isDigit(ch)){
                    searchF.setText(" ");
                    JOptionPane.showMessageDialog(null, "Please Enter Only Names or Surnames. Letters Only Allowed");
                    searchF.setText(" ");
                   }
               }
 });
like image 408
Lambros Avatar asked Feb 01 '26 10:02

Lambros


2 Answers

I have a JTextField that works perfectly fine when someone enters a number instead of a letter. My only problem is that that the number then does not dissappear.

  • KeyListener isn't proper Listener for Swing JComponents, nor for JTextComponents

  • use DocumentFilter for plain vanilla JTextField

  • use JFormattedTextField with Number Formatter

  • JOptionPane inside events fired from listener must be wrapped into invokeLater

like image 85
mKorbel Avatar answered Feb 03 '26 09:02

mKorbel


This is another way of coming at the issue, Consume the key event if it is a number, that way the user doesn't lose their input but you still get the message.

  if(Character.isDigit(ch)){
                JOptionPane.showMessageDialog(null, "Please Enter Only Names or Surnames. Letters Only Allowed");
             e.consume();
               }
like image 25
Levenal Avatar answered Feb 03 '26 08:02

Levenal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!