简体   繁体   中英

How do I put the form fields into a list to be able to iterate through them?

I want to iterate through this form's fields using an ArrayList , but I don't know how to do it.

Here is the image of the form:

And here is the code:

    private void btnTotalActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:


 double index=Double.parseDouble(txtIndexNou.getText())-      Double.parseDouble(txtIndexVechi.getText());
 txtIndexTotal.setText(Double.toString(index));
 txtCam1.setText(Double.toString(index));
 txtTotal1.setText(Double.toString((index *a)));

 double index1=Double.parseDouble(txtIndexNou2.getText())-Double.parseDouble(txtIndexVechi2.getText());
 txtIndexTotal.setText(Double.toString(index1));
 txtCam1.setText(Double.toString(index1));
 txtTotal1.setText(Double.toString((index1 *a))); 

 double index2=Double.parseDouble(txtIndexNou3.getText())-Double.parseDouble(txtIndexVechi3.getText());
 txtIndexTotal.setText(Double.toString(index2));
 txtCam1.setText(Double.toString(index2));
 txtTotal1.setText(Double.toString((index2 *a)));

 double index3=Double.parseDouble(txtIndexNou4.getText())-Double.parseDouble(txtIndexVechi4.getText());
 txtIndexTotal.setText(Double.toString(index3));
 txtCam1.setText(Double.toString(index3));
 txtTotal1.setText(Double.toString((index3 *a)));

 double index4=Double.parseDouble(txtIndexNou5.getText())-Double.parseDouble(txtIndexVechi5.getText());
 txtIndexTotal.setText(Double.toString(index4));
 txtCam1.setText(Double.toString(index4));
 txtTotal1.setText(Double.toString((index4 *a)));
}

txtIndexNou and txtIndexVechi which I assume are some kind of text input must be created with a loop and there reference stored in an ArrayList, then when you want to read back their values, just iterate through the list.

Edit 1

To optimize code duplication, you can encapsulate your logic into a method.

There is no need to have a list. I believe what you want to do is reduce code duplication. All you need to do is to create a separate method to do all the staff you are duplicating:

public void doStuff(String input1, String input2){
double index=Double.parseDouble(input1)-Double.parseDouble(input2);
 txtIndexTotal.setText(Double.toString(index));
 txtCam1.setText(Double.toString(index));
 txtTotal1.setText(Double.toString((index*a)));
}

And then call it:

doStuff(txtIndexNou.getText(), txtIndexVechi.getText());
doStuff(txtIndexNou2.getText(), txtIndexVechi2.getText());
doStuff(txtIndexNou3.getText(), txtIndexVechi3.getText());
doStuff(txtIndexNou4.getText(), txtIndexVechi4.getText());
doStuff(txtIndexNou5.getText(), txtIndexVechi5.getText());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM