views:

541

answers:

2

Hi there,

In order to initialise all JTextfFields on a JPanlel when users click a "clear button" I need to loop through the JPanel (instead of setting all individual field to ""). Can someone please show me how to use a For Each loop in order to iterate thru the JPanel in search of JTextFields.

Very much appreciated

Dallag.

+6  A: 
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("");
}
kd304
Does that clear combo boxes too? (Might as well be static, btw.)
Tom Hawtin - tackline
JComboBox (extends JComponent) and JTextField (extends JTextComponent which extends JComponent) are on two different paths
kd304
I checked the source of JComboBox and I don't see any place where JComboBox adds its editor component to its components list.
kd304
Thank you so very much kd304 it worked a treat.Just had to add import java.awt.*;import javax.swing.*;import java.awt.Component;
Dallag
Yes, sorry. I'm too customed to CTRL+SHIFT+O in Eclipse to organize my imports.
kd304
+1  A: 

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.

Tom Hawtin - tackline
+1 for the idea of having list of interresting components
kd304
Hi there,Thank a lot. This sounds impressive but I would not know how to implement your solution. Comcrete examples are worth a 1000 words.Very much appreciated. Dallag.
Dallag
And to push it further, I once tried an annotation based solution for fun. I annotated my fields in the class with my @SaveContent and used a reflective approach to load/save contents of the annotated components.
kd304