javafxcheckboximageviewgraphicscontext

How to show and hide Images on check/unchecking of a Checkbox?


I'm trying to have a few CheckBoxes visualize ingredients on a pizza in this javafx app. The Pizza is a ImageView. But I don't know how I will go about adding ingredients. Lets talk about salami for a second!

My first idea was to do this on my setOnAction of my CheckBox salami: (gc being my graphics context)

Image salami1 = new Image("salami.png");
gc.setFill(new ImagePattern(salami1);
gc.fillOval(250, 200, 60, 60);

(I tried just adding another ImageView on top instead, but even though It was a .png which transparent background the background would still show. So I tried this instead. Since I will only go for cheese, salami this would be fine too. This is very basic and supposed to be just for practice on my side.)

However, How do I make the salami disappear again once I uncheck the box? I'm aware of gc.clearRect() but that's it. I'm clueless as on how to do this upon unchecking the box. Thanks in advance


Solution

  • You can do this pretty simply by binding the ImageView's visible property to the selected property of the appropriate CheckBox.

    Here's a quick sample:

    import javafx.application.Application;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.CheckBox;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class Main extends Application {
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) {
    
            // Just creating a sample interface
            VBox root = new VBox(5);
            root.setPadding(new Insets(5));
            CheckBox chkSalami = new CheckBox("Salami");
            ImageView imgSalami = new ImageView("salami.png");
    
            // Bind the salami image's "visible" property to the checkbox's "selected" property
            imgSalami.visibleProperty().bind(chkSalami.selectedProperty());
    
            root.getChildren().addAll(chkSalami, imgSalami);
    
            primaryStage.setScene(new Scene(root));
            primaryStage.show();
        }
    }
    

    The important part is the binding line. This is the basic logic that this line performs:

    This means you do not need to mess around with adding any loops or ChangeListeners to the CheckBox; just bind each image to the matching checkbox.