• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

New to GUI, need help with actionListener and buttons

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..
 
Bartender
Posts: 1104
10
Netbeans IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Better to use the getSource() method (this compares against the instance and not string values):

 
Ranch Hand
Posts: 50
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic