dimanche 31 janvier 2021

JAVAFX How to update checkbox deselect after change?

Hi I am trying to write a JavaFX GUI application that allows the user to pick a set of pizza toppings using a set of check boxes. Assuming each topping cost 50 cents, and a plain pizza costs $10, display the cost of the pizza. Note that, once a topping is checked or unchecked, the cost of pizza should update automatically. I almost have it working but when I click multiple boxes the price changes, I am trying to + 0.50 cents per topping and if I de select check box -0,50 cents, but when I choose multiple check box it is adding more. How can I change this thanks.

import javafx.scene.control.CheckBox;
import javafx.scene.text.Text;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;


public class PizzaMenu extends VBox
{
    private double cost;
    private Text text;
    private CheckBox checkbox1, checkbox2, checkbox3, checkbox4, checkbox5, checkbox6;
    public PizzaMenu()
    {
        cost=10.00;
        text=new Text("Pizza Cost:" + cost);
        checkbox1 = new CheckBox("Extra Cheese");
        checkbox1.setOnAction(this::processCheckBox);
        checkbox2 = new CheckBox("Green Pepper");
        checkbox2.setOnAction(this::processCheckBox);
        checkbox3 = new CheckBox("Pepperoni");
        checkbox3.setOnAction(this::processCheckBox);
        checkbox4 = new CheckBox("Onion");
        checkbox4.setOnAction(this::processCheckBox);
        checkbox5 = new CheckBox("Sausage");
        checkbox5.setOnAction(this::processCheckBox);
        checkbox6 = new CheckBox("Anchovies");
        checkbox6.setOnAction(this::processCheckBox);
        //layout container 4 hbox, 2 vbox?
        HBox hSet1 = new HBox(checkbox1, checkbox2);
        hSet1.setAlignment(Pos.CENTER);
        HBox hSet2 = new HBox(checkbox3, checkbox4);
        hSet2.setAlignment(Pos.CENTER);
        HBox hSet3 = new HBox(checkbox5, checkbox6);
        hSet3.setAlignment(Pos.CENTER);
        HBox userCost = new HBox(text);
        userCost.setAlignment(Pos.CENTER);
        VBox vSet1 = new VBox(hSet1,hSet2,hSet3,userCost);
        vSet1.setAlignment(Pos.CENTER);
        setSpacing(20);
        getChildren().addAll(vSet1);
    }
    public void processCheckBox(ActionEvent event)
    {
        if(checkbox1.isSelected() || checkbox2.isSelected() || checkbox3.isSelected() || checkbox4.isSelected() || checkbox5.isSelected() || checkbox6.isSelected())
        {
            cost = cost + 0.50;
            text.setText("Pizza Cost:" + cost);
        }
        else if(!checkbox1.isSelected() || !checkbox2.isSelected() || !checkbox3.isSelected() || !checkbox4.isSelected() || !checkbox5.isSelected() || !checkbox6.isSelected())
        {
            cost = cost - 0.50;
            text.setText("Pizza Cost:" + cost);
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire