This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Getting reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting reference" Watch "Getting reference" New topic
Author

Getting reference

Vopli Vidoplyasova
Greenhorn

Joined: Jun 05, 2008
Posts: 26
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

Joined: Dec 17, 2003
Posts: 624

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

Joined: Jun 05, 2008
Posts: 26
Mark, thanks a lot!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19684
    
  20

"Slava G.",

Please read your private messages regarding an important announcement.

Thank you,

Rob


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
Don't get me started about those stupid light bulbs.
 
subject: Getting reference