• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New to GUI, need help with actionListener and buttons

 
D Heaney
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1101
10
Java Netbeans IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Better to use the getSource() method (this compares against the instance and not string values):

 
Nam Ha
Ranch Hand
Posts: 50
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
A Thakur
Greenhorn
Posts: 20
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic