This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes New to GUI, need help with actionListener and buttons Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "New to GUI, need help with actionListener and buttons" Watch "New to GUI, need help with actionListener and buttons" New topic
Author

New to GUI, need help with actionListener and buttons

D Heaney
Greenhorn

Joined: Aug 30, 2011
Posts: 2
I'm trying to use the same actionlistener for multiple buttons (two to start with). Here is my code:


Is there any way I can tell which button was pressed in the actionPerformed method? Instead of the way I'm doing it just now. I don't want to have to add an if statement for every button I create, I've been looking around for a while but can't seem to find anything.
Thanks in advance..
Ranganathan Kaliyur Mannar
Bartender

Joined: Oct 16, 2003
Posts: 1076
    
  10

Better to use the getSource() method (this compares against the instance and not string values):



Ranga.
SCJP 1.4, OCMJEA/SCEA 5.0.
Nam Ha
Ranch Hand

Joined: Aug 05, 2011
Posts: 50

Hi Foamy Caramel,

I think you should use a common action listener if all the buttons do the same thing, regardless of buttons.
I prefer using separate action listeners for each buttons, and wrap the common things into a method.


Java Object Creation
A Thakur
Greenhorn

Joined: Apr 06, 2010
Posts: 20
There are 2 ways of implementing ActionListener:

Option 1: To have common ActionListener Implemented


OPTION 2: To have individual actionlisteners


See which one is better for you. Both approaches have same end-results.

Thanks.


SCJP 5.0
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38045
    
  22
The version with one listener and getSource() is by no means object-oriented programming, even though you see it in many books.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: New to GUI, need help with actionListener and buttons
 
Similar Threads
how to get paintComponent to respond to a variety of events
How to add two buttons in each row?
code error
JButton button
Swing and Thread nightmare. Please help.