Javafx 使用复选框更改订单
我正在开发一个应用程序,在这个应用程序中,如果用户选中复选框,矩形的顺序就会改变,比如蓝色矩形排在第一位,红色第二位 下面是示例代码。我尝试了“设置”,但没有成功,显然我在复制孩子!!我必须将侦听器添加到框中吗?请 多谢各位Javafx 使用复选框更改订单,javafx,Javafx,我正在开发一个应用程序,在这个应用程序中,如果用户选中复选框,矩形的顺序就会改变,比如蓝色矩形排在第一位,红色第二位 下面是示例代码。我尝试了“设置”,但没有成功,显然我在复制孩子!!我必须将侦听器添加到框中吗?请 多谢各位 public class Main extends Application{ @Override public void start(Stage primaryStage) { // Displaying all t
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);
}
}
在添加新子项后,首先使用clear()方法删除h1中的重复子项,如下所示:
box.setOnAction((e) -> {
if (box.isSelected()) {
h1.getChildren().clear();
h1.getChildren().addAll(rect2, rect1, box);
}
});
哇,非常感谢Keyurt非常感谢,但如果我可以问另一个与此相关的问题,如果我有第二个复选框,并且在该复选框上我希望矩形倒置(如在VBox中),我该如何做?VBox p=new VBox();setOnAction((e)->{if(box1.isSelected()){p.getChildren().addAll(rect1,rect2,box,box1);});我试过了,但一切都消失了。VBox p=new VBox();box1.setOnAction((e)->{if(box1.isSelected()){p.getChildren().clear();p.getChildren().addAll(rect1,rect2,box,box1);border.getChildren().clear();border.getChildren().add(p);});