0

Not sure if this is even remotely possible, but...

I have a jFrame with 10 different Textfields. Elequently named tf1, tf2, tf3...

What I'd LOVE to do is be able to reference them dynamically. Something like:

int i = 1;

while (i<11) {
    tf[i].settext("blah - " + i);
}

Any ideas? If anybody knows of a working example it'd be great.

4
  • why not store the 10 textFields in an array at the program start ? this code will work if the array name is "tf" Commented Nov 8, 2015 at 17:53
  • I really have no idea how to do that... I mean I can work with arrays (ie: String, int, doubles...), but are you talking about creating an array of textFields at runtime or somehow storing the existing textFields on my panel in an array? Commented Nov 8, 2015 at 18:19
  • I can work with arrays (ie: String, int, doubles...), - so why would an Array of JTextFields be any different? are you talking about creating an array of textFields at runtime - well if you want to work with an array (of any type) then you need to create the Array. So you create the Array, use a loop to create the text field and add the text field to the Array and the panel. Commented Nov 8, 2015 at 19:00
  • Hey thanks for that. Between your description and the answer below, I'm pretty sure I can work it out. Thanks! Commented Nov 8, 2015 at 20:56

1 Answer 1

1

If you want to set the text of all the textfields in a JFrame:

Component ca[] = getContentPane().getComponents();
System.out.println("ca = " + Arrays.toString(ca));
int i = 0;
for(Component c: ca) {
    if(JTextField.class.isAssignableFrom(c.getClass())) {
        JTextField tf = (JTextField) c;
        tf.setText("blah -"+(++i));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.