简体   繁体   中英

Using event handler in JAVA FX

In our class we we're given an assignment, we are supposed to create a pizza GUI using check boxes for toppings and radio buttons for pizza size and type.

We'll I've already created the basic foundation for my GUI and I've even implemented the logic, but I've run into a small issue.

In my program I want the user to select their toppings, pizza size and pizza type. After the user has completed said task I want them to click process selection and the information along with sales prices will be added into a new text area.

Unfortunately, even when calling the string (where I hold everything) in the new textarea I still receive a blank space.

Thus, I am left to believe my I have not properly called for an action in the handler. I am also receiving a warning "event parameter not used"

I've cut out a snipet of my code below, as you can see I am attempting to store all the data in ordertext and then call it in my new text area orderscreen. I'm hoping someone can spot the mistake I've made, or give me some insight as to what I'm overlooking. Thank You

    TextArea orderscreen = new TextArea();
    orderscreen.setPrefColumnCount(50);
    orderscreen.setPrefRowCount(7);    
    grid.add(orderscreen, 0, 4);
    orderscreen.setText(ordertext);

          btn.setOnAction((ActionEvent event) -> {
              String mytoppings = "";
              double mytopcost = 0.0;

              if (chkTom.isSelected()) {
                  mytoppings = mytoppings + "Tomato "; // Topping
                  mytopcost += 1.50; // price
              }

              if (chkGP.isSelected()) {
                  mytoppings = mytoppings + "Green Peppers "; // Topping
                  mytopcost += 1.50; // pice
              }

              if (chkBO.isSelected()) {
                  mytoppings = mytoppings + "Black Olives "; // Topping
                  mytopcost += 1.50; // pice
              }

              if (chkMR.isSelected()) {
                  mytoppings = mytoppings + "MushRooms "; // Topping
                  mytopcost += 1.50; // pice
              }

              if (chkEC.isSelected()) {
                  mytoppings = mytoppings + "Extra Cheese "; // Topping
                  mytopcost += 1.50; // pice
              }

              if (chkPep.isSelected()) {
                  mytoppings = mytoppings + "Peppeoni "; // Topping
                  mytopcost += 1.50; // pice
              }

              if (chkSS.isSelected()) {
                  mytoppings = mytoppings + "Sausage "; // Topping
                  mytopcost += 1.50; // pice

              }
              else {
                  mytoppings = mytoppings + "No toppings selected ";
              }


              //Pizza Types

              String mypizzatype = "";
              // rbTC.setOnAction(e -> {
              if (rbTC.isSelected()) {
                  mypizzatype = mypizzatype + "Thin Crust "; // Type
              }
              // });

              //rbMC.setOnAction(e -> {
              if (rbMC.isSelected()) {
                  mypizzatype = mypizzatype + "Medium Crust "; // Type
              }
              // });

              if (rbP.isSelected()) {
                  mypizzatype = mypizzatype + "Pan "; // Type
              }

              // PIZZA SIZES
              String mypizzasize = "";
              Double smpzcost = 6.50;
              Double mdpzcost = 8.50;
              Double lgpzcost = 10.00;

              if (rbSM.isSelected()) {
                  mypizzatype = mypizzasize + "Small "; // Type
                  order = smpzcost;
              }

              if (rbMD.isSelected()) {
                  mypizzatype = mypizzasize + "Medium "; // Type
                  order = mdpzcost;
              }

              if (rbLG.isSelected()) {
                  mypizzatype = mypizzasize + "Large "; // Type
                  order = lgpzcost;
              }

              ordertext =  ("Your Order: "
                      + "\nPizza type: " + mypizzatype
                      + "\nPizza Size: " + mypizzasize
                      + "\nToppings: " + mytoppings
                      + "\nAmount Due: " + (order + mytopcost));
              System.out.println("Order Processed");
              //orderscreen.clear(); // WILL CLEAR
    });

I just fixed the problem

orderscreen.setText(ordertext);

needed to replace

ordertext =  ("Your Order: "
     + "\nPizza type: " + mypizzatype
     + "\nPizza Size: " + mypizzasize
     + "\nToppings: " + mytoppings
     + "\nAmount Due: " + (order + mytopcost));
orderscreen.setText(ordertext);

I also needed to change

mypizzatype = mypizzasize to mypizzasize= mypizzasize

No need for event handlers. in javafx you can use bindings.

I created simple demo that shows how to bind gui controls( RadioButtons , ChoiceBox ) to property in model class and bind it to TextArea :

package demo;

import javafx.application.Application;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

class User {
    private StringProperty order = new SimpleStringProperty();

    public String getOrder() {
        return order.get();
    }

    public void setOrder(String order) {
        this.order.set(order);
    }

    public StringProperty orderProperty() {
        return order;
    }
}

public class Demo extends Application {

    private User user = new User();

    @Override
    public void start(Stage stage) throws Exception {

        RadioButton tomatoButton = new RadioButton("Tomato");
        RadioButton pepperButton = new RadioButton("Pepper");
        RadioButton mushroomButton = new RadioButton("Mushrooms");

        ChoiceBox<String> pizzaType = new ChoiceBox<String>();
        pizzaType.getItems().addAll("", "Small", "Medium", "Large");
        pizzaType.getSelectionModel().selectFirst();

        HBox topHBox = new HBox(15.0, tomatoButton, pepperButton, mushroomButton, pizzaType);

        // create custom Binding that binds selection of radio buttons and choice box
        StringBinding orderBinding = createOrderBinding(tomatoButton.selectedProperty(), pepperButton.selectedProperty(), mushroomButton.selectedProperty(), pizzaType.getSelectionModel().selectedItemProperty());
        // bind orderBinding to orderProperty of User
        user.orderProperty().bind(orderBinding);

        TextArea orderArea = new TextArea();
        // bind orderProperty of User to textProperty of TextArea
        orderArea.textProperty().bindBidirectional(user.orderProperty());

        BorderPane root = new BorderPane();
        root.setTop(topHBox);
        root.setCenter(orderArea);

        Scene scene = new Scene(root, 400, 300);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * Creates StringBinding between 4 provided arguments. Binding means that when value of one bound property is changed the whole binding is recomputed in computeValue method.
     * The value of computeValue is bound to User.orderProperty 
     */
    public StringBinding createOrderBinding(BooleanProperty tomato, BooleanProperty pepper, BooleanProperty mushroom, ReadOnlyObjectProperty<String> selectedPizzaType) {
        StringBinding binding = new StringBinding() {
            {
                // bind 4 provided properties.
                super.bind(tomato, pepper, mushroom, selectedPizzaType);
            }

            /* 
             * Fires each time bound property is modified. 
             */
            @Override
            protected String computeValue() {
                StringBuilder sb = new StringBuilder("Pizza content:\n");

                if (tomato.get())
                    sb.append("\tTomato\n");
                if (pepper.get())
                    sb.append("\tPepper\n");
                if (mushroom.get())
                    sb.append("\tMushroom\n");

                sb.append("Pizza type:\n").append("\t" + selectedPizzaType.get());
                return sb.toString();
            }
        };
        return binding;
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

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