Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array of Jbutton - how to use event.getSource()

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So....

Assuming I have an array of buttons (30) how can I tell which one is pressed when it gets to the actionPerformed area.

say I have this class:

Class ABC implements ActionListener
{

private JButton myButton[] = new JButton ("na");

public ABC()
{
//initilizing

}
.
.
.
if (event.getSource()==myButton[i])
{
//Question - what is i ???
// do somthing here
}

do i have to write 30 if (event.getSource()

thanks for any help
 
Dror Guzman
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do this:

public void actionPerformed(ActionEvent e){

for(int i=0; i<MyButton.length; i++){
if(e.getSource() == MyButton[i])
// do your event here.....
}
}
 
Jeff Grant
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dror is correct assuming that your array is globally available.

I have run into a similar question as this topic numerous times dealing with either arrays which are not globally accessable or the JButton (or whatever) were not saved at all as the screen was dynamically created. In this case I would use JButton.setActionCommand(String) where the String I would give it would be which button it is... ie: Button 1, Button 2, etc..
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I typically prefer to have one ActionListener per button.

How do the buttons get created, and what should happen if you press them?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like one action listener per button. I also like an alternative with one action listener per window and a command per button.

This could just as easily be a listener per button since the code is so darned short. I tend to use "collection of commands to replace if-else-if" a lot. It might be the "when your only tool is a hammer everything looks like a nail" syndrome.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Command solution looks nice if you want to decouple the creation of the buttons from the definition of what the buttons actually do (for example if you build some kind of reusable gui).

Otherwise it just seems to be more complex and opens the door for bugs that can't happen with the one-listener-per-button approach (such as not finding a command for a button), without any benefits?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic