for (Component c : pane.getComponents()) { if (c instanceof JTextField) { ((JTextField)c).setText(""); } }
But if you have more deeply nested JTextFields, you can 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: Sample for Tom Hawtin - the suggestion for the link should be to have a list in your frame class:
List<JTextField> fieldsToClear = new LinkedList<JTextField>();
and when you initialize individual text fields, add them to this list:
someField = new JTextField("Edit me"); { fieldsToClear.add(someField); }
and when the user clicks the clear button, simply:
for (JTextField tf : fieldsToClear) { tf.setText(""); }
source share