Search code examples
javaswingkeylistenerjpasswordfield

JPasswordField and KeyListener


Can anyone help me with this code as I am a newbie in Java. I found this code on the web and I want to understand what it does?

pass = new JPasswordField(10);
    pass.addKeyListener(new KeyListener(){
            @Override
            public void keyTyped(KeyEvent e) {
                if(e.getKeyChar()==KeyEvent.VK_ENTER){
                    OKButton.doClick();
                }
            }

            @Override
            public void keyPressed(KeyEvent e) {
                //Do Nothing
            }

            @Override
            public void keyReleased(KeyEvent e) {
                //Do Nothing
            }

    });

As I understand it creates a text where everything I type is not visible, and I see bullets instead. Whats the purpose of the KeyListener? To identify the letters pressed?


Solution

  • This if(e.getKeyChar()==KeyEvent.VK_ENTER) checks whether the Key pressed is ENTER key or not.

    If user pressed ENTER KEY the java code automatically presses OK Button.

    For further understanding take a look at How to Write a Key Listener.