Java- Reading whether a checkbox is checked or not

后端 未结 1 1319
时光说笑
时光说笑 2020-12-21 09:40

My program compiles and runs, but here is my problem. I have a checkbox set up for each item, but I only need it to total the items that are checked and not all of the items

相关标签:
1条回答
  • 2020-12-21 10:11

    Because you are never checking for selected state of checkBoxes. It should be something like this:

    double total = 0;
    if(ClothingCheckBox.isSelected() && !ClothingField.getText().isEmpty()) {
        total += Double.parseDouble(ClothingField.getText());
    }
    if(BooksCheckBox.isSelected() && !BooksField.getText().isEmpty()) {
        total += Double.parseDouble(BooksField.getText());
    }
    if(SuppliesCheckBox.isSelected() && !SuppliesField.getText().isEmpty()){
        total += Double.parseDouble(SuppliesField.getText());
    }
    if(MealPlanCheckBox.isSelected() && !MealPlanField.getText().isEmpty()){
        total += Double.parseDouble(MealPlanField.getText());
    }
    if(InternetAccessCheckBox.isSelected() && !InternetAccessField.getText().isEmpty()){            
         total += Double.parseDouble(InternetAccessField.getText());
    }
    total = total * 100;
    DecimalFormat df = new DecimalFormat("$#.00");
    TotalField.setText(df.format(total));
    

    Things I would like to suggest you:

    1. Learn java coding convention and use them.
    2. You should also check for blank values in text fields before parsing them to double. Note that this also doesn't ensure that value in text field is parsable to Double.
    3. It seems like you want to have only numeric value in textField. For that don't use JTextField, use JFormattedTextField.
    0 讨论(0)
提交回复
热议问题