• Post Reply Bookmark Topic Watch Topic
  • New Topic

ActionListener  RSS feed

 
John Paul Griffin
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is my code and my problem is when i press AshWilliams on the hero's drop down menu the Cloud one comes up also and when i press the Cloud one the AshWIlliams one comes up. i dont know what im doing wrong
any help would be greatly appreciated




 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi John,

Welcome to the Ranch! For the future, please UseCodeTags(<-- read link). I added them to your post for now so you can see how much more readable they make your code.

As to your problem:

You set the String variable JMenuItem to null. Then you set ashWilliams and cloud variables to null. Then you check if ashWilliams is the same as JMenuItem, and since they are both null, the answer is true, so the ashWilliams work is done. Then you compare cloud to JMenuItem, and since they are both null the condition is true, you also do the cloud work.

There are a couple things wrong with this:
1) you should never have a variable with the same name as a class. The String variable named JMenuItem needs to be named something else - something that describes what it is supposed to be (like 'selectedMenuItem' or whatever).
2) The best approach for these sorts of things (multiple buttons with different actions) is to have different ActionListeners for each button. Have one ActionListener that just does the ashWilliams work and assign it to the ashWilliams button. Have a different ActionListener which just does the cloud work and add it to the cloud button. That way you can never have cross talk and don't have to check in the listener which button was pushed.
3) If you do need to use a single ActionListener for some reason, you need to do a couple of things:
-- first, use the methods provided by the ActionEvent (<-- link to API) to determine which work to do. Don't rely on some other variable, because how did that variable get set (hint: it didn't if you didn't set it)? See the API for ActionEvent to see if you can find the method to use.
-- second, make your conditions exclusive so you know only one action will be done at a time. For example, use the if () {} else if () {} else {} construct rather a series of if {} constructs. It will make your intent more clear (only one thing can be done).
 
Abhisek Pattnaik
Greenhorn
Posts: 3
Chrome IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use inner classes to implement two actionPerformed methods
OR
use Anonymous Classes
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!