mardi 21 novembre 2017

Checkbox EventHandler not changing text in label (JavaFX)

I'm just learning Java, things have been going well thus far. I am learning the basics of JavaFX and wrote a program that just shows some Checkboxes controls and Labels. I am trying to get the Label called response to change text when a user clicks on one(or any) of the checkbox. The code below shows only EventHandler for bananaCB checkbox.

public class Main extends Application implements EventHandler {
private Label title;
private Label response;
private Label selected;
private CheckBox bananaCB;
private CheckBox mangoCB;
private CheckBox papayaCB;
private CheckBox grapfruitCB;
private String fruits;

@Override
public void start(Stage primaryStage) throws Exception{
    primaryStage.setTitle("Favorite Fruit");

    title = new Label("What fruits do you like?");
    response = new Label("");
    selected = new Label("");

    bananaCB = new CheckBox("Banana");
    mangoCB = new CheckBox("Mango");
    papayaCB = new CheckBox("Papaya");
    grapfruitCB = new CheckBox("Grapfruit");


    //Setup the stage and Scene
    FlowPane flowPaneRoot = new FlowPane(Orientation.VERTICAL,5,5);
    flowPaneRoot.setAlignment(Pos.CENTER);

    //We add all of our controls to flowPaneRoot
    flowPaneRoot.getChildren().add(title);
    flowPaneRoot.getChildren().addAll(bananaCB,mangoCB,papayaCB,grapfruitCB);
    flowPaneRoot.getChildren().add(response);
    flowPaneRoot.getChildren().add(selected);


    //Attach eventListeners to our checkboxes.


    Scene scene = new Scene(flowPaneRoot,400,250);
    primaryStage.setScene(scene);
    primaryStage.show();

}

public void showAll(){
    fruits = "";
}


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

@Override
public void handle(Event event) {
    Object fruitSelected = event.getSource();
    if (bananaCB.equals(fruitSelected)) {
        if (bananaCB.isSelected()) {
            response.setText("Banana Selected");
        } else {
            response.setText("Banana cleared");
        }
    }

}

}

I did try an setOnAction eventhandler and it worked as expected. I had it commented out in the code above but it messed up the way it looked. I'll post it here.

        bananaCB.setOnAction(new EventHandler<ActionEvent>() {
        @Override
       public void handle(ActionEvent event) {
            response.setText("Banana Selected");
        }
    });




Aucun commentaire:

Enregistrer un commentaire