Loop through JPanel

To initialize all JTextfField to JPanel when users click the Clear button, I need to go through JPanel (instead of setting all the individual fields to "").

How can I use a for loop for each loop to iterate through JPanel in search of JTextField s?

+5
source share
2 answers
 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(""); } 
+15
source

While another answer shows a direct way to solve your problem, your question implies a poor solution.

It is usually required that static dependencies between layers be one way. You need to get getCommponents package. Casting (subject to generation) is an easy way to see if something went wrong.

Therefore, when you create text fields for a form, add them to the list, which will be cleared in a clear operation, and also add them to the panel. Of course, there are other things in the real code that you want to do with them. In real code, you probably want to deal with models (possibly Document ), not JComponent s.

+1
source

Source: https://habr.com/ru/post/904098/


All Articles