Hi all, I am trying to learn eventHandling in Java and have a doubt in the following code snippet. When i run it and press + or - key, it has no response. What is my mistake? where should i register the KeyListener interface?
First things first. You have used the MouseListener for you JButtons. For what you are doing you should be using the ActionListener interface instead. For the second thing, you can't really do what you are wanting to do with the KeyListener. Basically, you are trying to register a global KeyListener on the entire app. Swing won't work this way.
See this thread for similar discussion and viable solutions to your problem.
Thank you for your help Gregg, But i did not understand why should i use ActionListener instead of MouseListener? I have added two buttons and MouseListeners and it works fine? Why is it not ok? Cheers.
Originally posted by Kudret Serin: Thank you for your help Gregg, But i did not understand why should i use ActionListener instead of MouseListener? I have added two buttons and MouseListeners and it works fine? Why is it not ok? Cheers.
It's not that it isn't "OK" but what if your JButton has the focus and the user hits the Enter key (or space depending on platform). Nothing will happen if you are using MouseListener because the button is only listening for mouse events. By using ActionListener you are basically listing for pressed button events on the JButton regardless of what caused the action to happen.