Reputation: 153
i am working on an application in which if user select the CheckBox the Order of rectangle is changed, like Blue Rectangle comes first and red second.
Here is example code. I tried with "setOnAcation" it didn't work obviously i am duplicating child!! do i have to add listener to box? Please..
Thank you
public class Main extends Application{
@Override
public void start(Stage primaryStage) {
// Displaying all the functions in Scene
StackPane border = new StackPane();
Scene scene = new Scene(border, 750, 500);
primaryStage.setTitle("BorderPane");
primaryStage.setScene(scene);
primaryStage.show();
HBox h1 = new HBox(20);
h1.setPadding(new Insets(20));
CheckBox box = new CheckBox("Switch Places");
Rectangle rect1 = new Rectangle(200,200);
rect1.setFill(null);
rect1.setStroke(Color.RED);
Rectangle rect2 = new Rectangle(200,200);
rect2.setFill(null);
rect2.setStroke(Color.BLUE);
h1.getChildren().addAll(rect1,rect2,box);
box.setOnAction((e)->{
if (box.isSelected()){
h1.getChildren().addAll(rect2,rect1,box);
}
else{
System.out.println("Checkbox1 is not selected");
}
});
border.getChildren().add(h1);
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Upvotes: 1
Views: 69
Reputation: 1544
First remove duplicate child in h1 using clear() method after add a new child as:
box.setOnAction((e) -> {
if (box.isSelected()) {
h1.getChildren().clear();
h1.getChildren().addAll(rect2, rect1, box);
}
});
Upvotes: 1