JavaFX:带有关闭按钮的HBox

时间:2017-11-04 09:44:19

标签: java button javafx hbox

是否可以设置一个带有关闭按钮的HBox(即用于删除HBox的子按钮)?我打算将其实现为像这样的东西:

See image here.

我想创建一个自己的类,它继承自HBox类,并且在实例化后已经有一个关闭按钮。 关闭按钮需要从HBox (在这种情况下,HBox父级)的父级移除VBox不隐藏< / strong>即可。但我不确定是否有可能。

如果可能,应该如何实现关闭按钮setOnAction

1 个答案:

答案 0 :(得分:1)

当然有可能:

EventHandler<ActionEvent> handler = event -> {
    // get button that triggered the action
    Node n = (Node) event.getSource();

    // get node to remove
    Node p = n.getParent();

    // remove p from parent's child list
    ((Pane) p.getParent()).getChildren().remove(p);
};
Button button = new Button("x");
button.setOnAction(handler);

请注意,事件处理程序的相同实例可以重复用于多个关闭按钮,因为您获得了从事件对象中单击的按钮。