The moose likes Swing / AWT / SWT and the fly likes Creating JLabel and JTextfields at runtime Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Creating JLabel and JTextfields at runtime" Watch "Creating JLabel and JTextfields at runtime" New topic

Creating JLabel and JTextfields at runtime

Kunal Lakhani
Ranch Hand

Joined: Jun 05, 2010
Posts: 622
In my application, a db query is executed, gets the ids from db, & stores it in a list.
Then those many numbers of JLabel and JTextfields is created. Here is what i tried :

The list contains 2 numbers, 1 & 2. So the code creates 2 jlabels 1 & 2 with their respective textfields. So far, its good. But, how will i get their values after SUBMIT (JButton) is pressed? (JTextfields and Jlabels are declared inside the method, of whose code i have posted. )>

Yohan Weerasinghe
Ranch Hand

Joined: Oct 07, 2010
Posts: 507

values can be retrieved by getText() method, isn't it?

Are you better than me? Then please show me my mistakes..
Kemal Sokolovic

Joined: Jun 19, 2010
Posts: 825

If I understood your problem well, you're asking how to access specific component (in this case JTextField) if you added it dynamically to your panel. Am I right?

If that is the case, once you handle the appropriate event (click on a button) you will need to iterate over all components placed inside your container and find the one that matches the name you are looking for. Once you access it, you can get its content with getText()

The quieter you are, the more you are able to hear.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

When you create one of those components and add it to your GUI, keep a reference to it.

That doesn't mean you have to create a new variable to store the reference in. But you can certainly add it to a list of references, or something like that.
Kunal Lakhani
Ranch Hand

Joined: Jun 05, 2010
Posts: 622
Thanks all for your replies. I have created a list of JTextFields and will get the values of JTextFields by iterating through the list.

Its something like this :

I agree. Here's the link:
subject: Creating JLabel and JTextfields at runtime
It's not a secret anymore!