• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting reference

 
Vopli Vidoplyasova
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would anybody please help me figure out next? If I create 10 buttons and add them to a panel using something like this:




How do I get a reference to, let's say, "Button 7" if I need to invoke a method on it?

Thank you.
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could call the panel.getComponents() method which would return an array of all the components that are part of the panel. But then you need to iterate through them and try to figure out which is the button you need if you need a specific one. Plus it will return any other components added to the panel, such as a label. So you would need to do an "instance of" check on each component as you iterate through to see if it is a button. An then you would need to cast it to a JButton if you need to call a method specific to a Button class.

The easier way would be to retain a reference to each button as you add it. You could store them in a List, or a Map:



So you can get an individual button if needed; or iterate through them all if you need to do something to all of them.
[ August 14, 2008: Message edited by: Mark Vedder ]
 
Vopli Vidoplyasova
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark, thanks a lot!
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Slava G.",

Please read your private messages regarding an important announcement.

Thank you,

Rob
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic