0

我有一个 VBox 的根节点。我还有一个使用窗格和按钮创建的复合节点。复合节点的多个实例被添加到 VBox。我试图找到一种在触发内部按钮时删除每个复合节点的方法。但我没能找到方法。这是我的代码,有人可以帮我吗?

@Override
public void start(Stage primaryStage) {
    VBox root = new VBox();
    root.setAlignment(Pos.TOP_CENTER);
    root.setSpacing(10);

    Scene scene = new Scene(root, 300, 700);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

    // 10 Non reffered instances will be added to the VBox(root)
    for (int i=0; i<10; i++) {
        Pane compositeChild = new Pane();
        compositeChild.setPrefWidth(300);
        compositeChild.setPrefHeight(40);
        compositeChild.setBorder(new Border(new BorderStroke(Color.CORAL, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));
        Button btn = new Button("Delete Me");
        btn.setPrefWidth(200);
        btn.setPrefHeight(30);
        btn.setLayoutX(50);
        btn.setLayoutY(5);

        // I want to find some code for below action event
        btn.setOnAction(e2 -> {
            //how can I remove only one compositeChild that the event fired From the root(VBox)
            ((Button)e2.getSource()).setText("I should be deleted??");
        });

        compositeChild.getChildren().add(btn);
        root.getChildren().add(compositeChild);
    }
}
4

2 回答 2

1

做就是了

btn.setOnAction(e2 -> {
    root.getChildren().remove(compositeChild);
});
于 2017-01-18T22:37:21.247 回答
1

你也可以这样做:

btn.setOnAction(e2 ->
{
    if (btn.getParent() == null || btn.getParent().getParent() == null)
        return;

    ((Pane)btn.getParent().getParent()).getChildren().remove(btn.getParent());
});
于 2017-01-19T01:25:16.497 回答