I created text fields in Java as following. When I click a "clear" button I want to clear all of these text fields at once.
private javax.swing.JTextField num1;
private javax.swing.JTextField num2;
private javax.swing.JTextField num3;
private javax.swing.JTextField num4;
private javax.swing.JTextField num5;
private javax.swing.JTextField num6;
private javax.swing.JTextField num7;
Now I want to know how to use a for loop to clear these all text fields like:
for(int i=1;1<7;i++){
num[i].settext(null);
}
Code like this:
private javax.swing.JTextField num1;
private javax.swing.JTextField num2;
private javax.swing.JTextField num3;
private javax.swing.JTextField num4;
private javax.swing.JTextField num5;
private javax.swing.JTextField num6;
private javax.swing.JTextField num7;
Is code that is crying out to be arranged and simplified by using collections or arrays. So if you use an array of JTextField or perhaps better an ArrayList<JTextField>
. Then clearing them all is trivial.
public static final int FIELD_LIST_COUNT = 7;
private List<JTextField> fieldList = new ArrayList<JTextField>();
// in constructor
for (int i = 0; i < FIELD_LIST_COUNT; i++) {
JTextField field = new JTextField();
fieldList.add(field);
fieldHolderJPanel.add(field); // some JPanel that holds the text fields
}
// clear method
public void clearFields() {
for (JTextField field : fieldList) {
field.setText("");
}
}