It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes Getting JComponents Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Getting JComponents" Watch "Getting JComponents" New topic

Getting JComponents

Nick Lebian

Joined: May 30, 2003
Posts: 9
How can I get the JComponentes of a GUI? With AWT it's easy, I just have to type
Component comp=this.getComponent(1);
But how does this work with swing? There isnt't a method like
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

JComponent extends Container which extends Component. getComponents() still does what you want in Swing.

[Jess in Action][AskingGoodQuestions]
Nick Lebian

Joined: May 30, 2003
Posts: 9
Thank you. But now I have the next problem. I can't read out the array of getComponents() in an other method:
public Text(List list, int gaps)
setLayout(new FlowLayout());
while (it.hasNext())
add(new JLabel((String);
if (it.hasNext())
add(new JTextField("",7));
public List readout()
Component comp[]=this.getComponents();
for(int i=1; i<2*gaps; i=i+2)
JTextField jtext=(JTextField)comp[i];
return result;
This doesn't work, the List result is empty. How can I get access to the JTextField Components and their content, in an other method where they were created?
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

Then you arn't doing something right... I can't tell what the 'gaps' variable is supposed to do in your component, but you should be looping through the entire array you get back from 'getComponents()' not '2*gaps'. Here is a short example that shows that this works :

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
I agree. Here's the link:
subject: Getting JComponents
It's not a secret anymore!