DnwAlgorithma
DnwAlgorithma

Reputation: 119

How to clear text fields using for loop in java

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

Upvotes: 2

Views: 13090

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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

Upvotes: 7

Azad
Azad

Reputation: 5055

You can easily get the components inside the container by container.getComponents() method with consider some important things:

  1. There may another container like JPanel.
  2. There may another component like JLabel,JButton,....

Use this method:

public void clearTextFields (Container container){

  for(Component c : container.getComponents()){
   if(c instanceof JTextField){
     JTextField f = (JTextField) c;
     f.setText("");
 } 
  else if (c instanceof Container)
     clearTextFields((Container)c);
}
}

Call the method like this:

clearTextFields(this.getContentPane());

Upvotes: 7

Related Questions