1

I want when user press enter button on keyboard, then program should function like when click on ok button.

My code:

public class T3 extends JFrame implements ActionListener {

JButton okBtn;

public T3() {
    this.setFocusable(true);
    this.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {
            // if enter button is pressed in keyboard, then show "Enter Button pressed" message
        }

        @Override
        public void keyPressed(KeyEvent e) {
            // if enter button is pressed in keyboard, then show "Enter Button pressed" message
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    add(createForm(), BorderLayout.NORTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new T3();
        }
    });
}

public JPanel createForm() {
    JPanel panel = new JPanel();
    okBtn = new JButton("Ok");
    okBtn.addActionListener(this);
    panel.add(okBtn);
    return panel;
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == okBtn) {
        System.out.println("Enter Button pressed");
    }
}
}

Now, Not react !

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sajad
  • 2,273
  • 11
  • 49
  • 92
  • Take a look to [KeyBindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – nachokk Oct 29 '13 at 19:53
  • possible duplicate of [Java KeyListener for JFrame is being unresponsive?](http://stackoverflow.com/questions/286727/java-keylistener-for-jframe-is-being-unresponsive) – Anubian Noob Jun 15 '14 at 23:29

1 Answers1

3

KeyListeners don't work on containers when a child component has the focus. You will need an application wide KeyListener. Check out this SO question:

Setting up application wide Key Listeners

Community
  • 1
  • 1
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287