aspose file tools*
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
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: 1096
    
  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: 40052
    
  28
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