• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamically adding components and later referring to them

 
anandh
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
myPanel.add(myTextField);
}
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
 
Shay Gaghe
Ranch Hand
Posts: 102
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
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
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
anandh,

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!

-Nate
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic