I have a JPanel
that have a lot of JTextFields
and JComboBoxes
and JRadioButtons
, so i want to make them all in the default values in one shot.
I used to empty every field one by one but this take lot of time, and maybe i miss some fields, or some times i can add another fields, so it is not practice at all.
public void empty(){
field1.setText("");
field2.setText("");
field3.setText("");
...
}
So is there any way to make all the fields empty in one shot?
Thank you.
If the JTextFields
are not all in the same container, this would be a possible approach:
private List<JTextField> allTextFields = new ArrayList<JTextField>();
private JTextField createNewTextField(String text) {
JTextField textField = new JTextField(text);
allTextFields.add(textField);
return textField;
}
private void resetAllTextFields(){
for (JTextField textField : allTextFields) {
textField.setText("");
}
}
..and then instead of using the constructor JTextField myTextField = new JTextField("content")
use JTextField myTextField = createNewTextField("content");
Your question is a bit broad, and no one-size-fits all solution is optimal, but I can say that iterating through a JPanel's components, and clearing all is not the best solution for several reasons, including:
Better is to strive to separate concerns, to reduce coupling of the model to the view, and for this reason, likely the cleanest solution is to try to separate your model from your view, à la MVC for instance, clear portions of the model that need to be clear, and in the control clear only those portions of the view bound to that section of the model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With