Search code examples
javaarraysswingcountingjcheckbox

update all TextFields each time a box is checked with java


I have a series of JCheckBoxes(1-20) and each is associated with a JTextField(1-20). I would like all textfields to be updated each time a box is checked. The fields are to be updated with the formula 100/(sum of checkboxes that are checked). So if checkbox1 is checked then textfield1 displays 100. If checkbox15 is also checked then textfield1 and textfield15 display 50. Right now when I check checkbox1 then textfield1 displays 100 and when I check checkbox2 is displays 50 but textbox1 remains at 100 instead of also updating to 50. What can I do to make all textfields simultaneously update?

es1-es20 are my textfields p1 is the textfield I am getting the 100 from. evensplit is my array of 20 textfields.

Also, it does work unless I declare my array each for each textfield. Where should I declare my array so that each actionevent can access it?

private void es1ActionPerformed(java.awt.event.ActionEvent evt) {
    JCheckBox evensplit[] = new JCheckBox[24];
    evensplit[0] = es1;
    evensplit[1] = es2;
    ...24 times

    int checknums = 0;

    for(int c = 0;c< evensplit.length; c++) {
        if(evensplit[c].isSelected()) {
            checknums++;
            double even = 100/checknums;
            p1.setText(String.valueOf(even));
        }
    }
}

private void es2ActionPerformed(java.awt.event.ActionEvent evt) {
    JCheckBox evensplit[] = new JCheckBox[24];
    evensplit[0] = es1;
    evensplit[1] = es2;
    ...24 times

    int checknums = 0;

    for(int c = 0;c< evensplit.length; c++) {
        if(evensplit[c].isSelected()) {
            checknums++;
            double even = 100/checknums;
            p2.setText(String.valueOf(even));
        }
    }

Thanks in advance for any help!


Solution

  • The value you want to set depends on testing all checkboxes, but you are setting the value (setText()) while you're still in the loop. You're going to have to loop through all the checkboxes to count the checked ones, THEN loop through all the fields to set values.

    To have one array accessible to both routines, declare it as an instance variable; it will be within the class, but outside either of the methods.