Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty all Fields Swing in one shot

Tags:

java

swing

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.

like image 479
YCF_L Avatar asked Feb 05 '23 11:02

YCF_L


2 Answers

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");

like image 51
user7291698 Avatar answered Feb 22 '23 19:02

user7291698


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:

  • You may later wish to add a component that is not cleared, or that is only cleared under certain conditions, and having code that directly clears components may make this hard to debug and fix.
  • Most GUI's have layers of JPanels, and if later you add a sub-JPanel, does this mean that you're going to want to recursively iterate through all components and clear them?

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.

like image 31
2 revs Avatar answered Feb 22 '23 19:02

2 revs