File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting reference" Watch "Getting reference" New topic

Getting reference

Vopli Vidoplyasova

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

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

Joined: Oct 27, 2005
Posts: 20279

"Slava G.",

Please read your private messages regarding an important announcement.

Thank you,


How To Ask Questions How To Answer Questions
It is sorta covered in the JavaRanch Style Guide.
subject: Getting reference
It's not a secret anymore!