Issue
Im trying to have a few CheckBoxes visualize ingredients on a pizza in this javafx app. The Pizza is a ImageView. But I dont 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 beeing 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 tho It was a .png wich 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? Im aware of gc.clearRect() but thats it. Im 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:
- Always set the
imgSalami
object's visibility to match whetherchkSalami
is selected.
This means you do not need to mess around with adding any loops or ChangeListener
s to the CheckBox
; just bind each image to the matching checkbox.
Answered By - Zephyr
Answer Checked By - Mary Flores (JavaFixing Volunteer)