Question

In order to initialize all JTextfFields on a JPanel when users click a "clear button", I need to loop through the JPanel (instead of setting all individual field to "").

How can I use a for-each loop in order to iterate through the JPanel in search of JTextFields?

Was it helpful?

Solution

for (Component c : pane.getComponents()) {
    if (c instanceof JTextField) { 
       ((JTextField)c).setText("");
    }
}

But if you have JTextFields more deeply nested, you could use the following recursive form:

void clearTextFields(Container container) {
    for (Component c : container.getComponents()) {
        if (c instanceof JTextField) {
           ((JTextField)c).setText("");
        } else
        if (c instanceof Container) {
           clearTextFields((Container)c);
        }
    }
}

Edit: A sample for Tom Hawtin - tackline suggestion would be to have list in your frame class:

List<JTextField> fieldsToClear = new LinkedList<JTextField>();

and when you initialize the individual text fields, add them to this list:

someField = new JTextField("Edit me");
{ fieldsToClear.add(someField); }

and when the user clicks on the clear button, just:

for (JTextField tf : fieldsToClear) {
    tf.setText("");
}

OTHER TIPS

Whilst another answer shows a direct way to solve your problem, your question is implying a poor solution.

Generally want static dependencies between layers to be one way. You should need to go a pack through getCommponents. Casting (assuming generics) is an easy way to see that something has gone wrong.

So when you create the text fields for a form, add them to the list to be cleared in a clear operation as well as adding them to the panel. Of course in real code there probably other things you want to do to them too. In real code you probably want to be dealing with models (possibly Document) rather than JComponents.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top