• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Need help with addActionListener

 
Ranch Hand
Posts: 37
IntelliJ IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everyone,

I have an array of JButtons, and I don't know how to determine which one was clicked. I know how to do it if each button had a different text (i.e. Ok, Cancel, etc.), but in my case they all have the same exact text (I'm writing a poker game).

Here is a sample of my code...



What can I do in the actionPerformed method in order to determine which button was pressed?

Thanks!
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
here are some of the ways you could do this

1. in actionPerformed() iterate the button array checking if it is the source
(the button array will need the necessary scope)


2. add a separate actionListener to each button, each with it's own actionPerformed(),
then have a separate method that takes an identifier as a parameter



3. create your own JButton, adding an ID
then, in actionPerformed you cast the source as MyButton, and get the ID
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you can also just set the action command for each of the buttons. But I like the solutions Michael posted above better
 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instead of option three above, you can use the myButton.setName("my button's name") to give each button an identifier. Then you use .getName() to retrieve the name when you need it.

Cheers,
Rachel
 
Steve Vittoria
Ranch Hand
Posts: 37
IntelliJ IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Awesome! Thanks Michael!

I tried both option 1 and 2. While option 1 results in less lines of code, I really like how clear and clean option 2 is.

Again thanks!
 
reply
    Bookmark Topic Watch Topic
  • New Topic