Search code examples
javaswingjtextfieldkeylistener

JTextField take twice the input, but why?


I wanna make a programmable calculator, i got the basic GUI, and now i'm trying to set up the buttons, and the display. My display text will be "0" basically and if the user type in a number, that number should to be displayed. I tried to do it with KeyListener, but if i press a key it will display the key twice. Why?

 textField.addKeyListener(new KeyListener(){
        boolean newNumber = true;

        public void keyTyped(KeyEvent e) {
        }

        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();


            if(keyCode == e.VK_BACK_SPACE && textField.getText().length() == 1){
                textField.setText("0");
                newNumber = true;
                }

            if(textField.getText().equals("0") && newNumber){
                textField.setText(KeyEvent.getKeyText(keyCode));
                newNumber = false;
            }
        }

        public void keyReleased(KeyEvent e) {
        }

    });

Before input:

enter image description here

After "1" input:

enter image description here


Solution

  • Here a simple solution:

    If you use keyPressed, you have to do something in keyReleased and this become complicated. keyTyped is a more simple way.

    You can use e.consume() to prevent having the double digit inserted.

        textField.addKeyListener(new KeyListener() {
    
            int codeDelete = KeyEvent.getExtendedKeyCodeForChar(KeyEvent.VK_DELETE);
            int codeBackSpace = KeyEvent.getExtendedKeyCodeForChar(KeyEvent.VK_BACK_SPACE);
    
            @Override
            public void keyTyped(KeyEvent e) {
    
                char keyChar = e.getKeyChar();
    
                if (textField.getText().length() == 0) {
                    textField.setText("0");
                }
                else if (textField.getText().equals("0") && keyChar != codeDelete && keyChar != codeBackSpace) {
                    textField.setText(String.valueOf(e.getKeyChar()));
                    e.consume();
                }
            }
    
            @Override
            public void keyPressed(KeyEvent e) {
            }
    
            @Override
            public void keyReleased(KeyEvent e) {
            }
    
        });