Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Event Handling

 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now i understand what you mean. Thanks a lot once again.
Cheers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic