首页 文章

JavaFX:带有关闭按钮的HBox

提问于
浏览
1

Is it possible to have a HBox with a close button (i.e. a child button with the purpose of removing the HBox)? 我打算把它实现成这样的东西:

See image here.

我想创建一个自己的类,它继承自 HBox 类,并且在实例化后已经有一个关闭按钮 . The close button needs to remove the HBox from the parent of the HBox (在这种情况下, VBox 父母), not hide it . 但我不确定是否有可能 .

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

1 回答

  • 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);
    

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

相关问题