File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes Event Handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Event Handling" Watch "Event Handling" New topic
Author

Event Handling

Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

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?


Thanks in advance for your help.
Cheers.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

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.


GenRocket - Experts at Building Test Data
Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

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.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

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.
Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

Now i understand what you mean. Thanks a lot once again.
Cheers.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Event Handling