Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 765
DnwAlgorithma Avatar asked Jan 29 '26 12:01

DnwAlgorithma


2 Answers

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("");
  }
}
like image 143
Hovercraft Full Of Eels Avatar answered Jan 31 '26 01:01

Hovercraft Full Of Eels


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());
like image 38
Azad Avatar answered Jan 31 '26 00:01

Azad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!