Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Swing / AWT / SWT and the fly likes Dynamically adding components and later referring to them Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Dynamically adding components and later referring to them" Watch "Dynamically adding components and later referring to them" New topic

Dynamically adding components and later referring to them


Joined: Sep 06, 2001
Posts: 22
I have a loop in my program where I add some textfields in the contentPane dynamically, because I don't know how many of them will be added. It depends on some variable, say some_var.
The code will be something similar to :
for(int i=0;i< some_var;i++)
contentPane.add(new JTextField());
How do I now access every individual JTextField component? (Because I added them anonymously). Is there any 'trick' of adding components dynamically and later operate on them?
Please help!
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15302

Most Components have a setName() method. Check the API to be sure. Here is one way you could do it. Surely not the only way, maybe not even the easiest.
While you are looping through your routine to add the components, give each component a name. And to be able to easily recall that variable name, well, here:
for (int i = 0; i < some_var; i++) {
//first, parse i into a string called say, myString
myTextField.setName("field" + myString);
Hope that makes a little since. Basically you are giving each field a name like field0, field1, field2, etc.
So you could create a listener that checks for which field you are in by name.

Happy Coding,
Gregg Bolinger

GenRocket - Experts at Building Test Data
Shay Gaghe
Ranch Hand

Joined: Sep 03, 2001
Posts: 102
As far as I see it there is no logic to do such of thing. Because if you add them anonymously later you have to convert each one of them to an object to getting access to . So I suggest to do an array of textfield which allows you to refer to them easily and its will be more readable.
Here is an example of one way to implement what you want, although I post it its not my suggestion:

As you can see you must to convert the component in 2 index to a JtextField to get access to.
Hope its help
Shay Gaghe

[This message has been edited by Shay Gaghe (edited October 21, 2001).]
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121


Please re-register with a name that follows the guidelines of the JavaRanch naming conventions. We require all registered user names to be in the form "first name" + space + "last name". Thanks!


Write once, run anywhere, because there's nowhere to hide! - /. A.C.
I agree. Here's the link:
subject: Dynamically adding components and later referring to them
It's not a secret anymore!