zari
zari

Reputation: 1739

Key Pressed Event

I want add a KeyEventListener to JButton which responds to Enter key, using following code segment:

   private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {
        if (evt.getKeyCode() == 10) {
           eventRegister();
        }
   }                                   

I pressed space bar instead of enter and the if condition set to true and the eventRegister invoked. Why? How could I prevent this manner?

Upvotes: 4

Views: 2878

Answers (3)

Pshemo
Pshemo

Reputation: 124215

You should use KeyBinding instead of KeyListeners.


But even if you are not, your current code should work like in this example.

JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
JButton button=new JButton("do something");
button.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == 10) {
                        System.out.println("it is ten");
                }
        }
});
frame.getContentPane().add(button);


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);

If you wont post complete (but short) example that can be used to reproduce your problem it will be almost impossible to say what you did wrong.

(I will try to edit this answer if you add more informations about your code).

Upvotes: 1

mKorbel
mKorbel

Reputation: 109815

  • don't to use KeyListener or MouseListener for JButton or JButtons JComponent, those events are implemented in API, or ButtonsModel, every can be testable, with to consume() of KeyEvent

  • JButton has implemented ENTER and SPACE key as accelator in KeyBindings

  • remove SPACE from KeyBindings, but not suggest that, I'm wouldn'd be confuse users, sure depends of

Upvotes: 6

Tala
Tala

Reputation: 8928

try to use

if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
....

"Key pressed" and "key released" events are lower-level and depend on the platform and keyboard layout.

Since java is cross platform, don't use hardcoded values for keyboard codes.

Upvotes: 0

Related Questions