Button 如何在动态用户界面中访问GUI元素

Button 如何在动态用户界面中访问GUI元素,button,javafx,Button,Javafx,我正在尝试开发一个动态用户界面。当用户单击某个指示器时,该指示器的图形将与一些操作按钮一起实例化。请参见图中的示例。图形与按钮一起在HBox中创建,然后添加到VBox中。我无法解决的问题是:单击按钮时,如何访问相应的元素 问题简单地归结为: Button buttonRemove = new Button (); buttonRemove.setMinWidth (80); buttonRemove.setText ("Remove"); buttonMap.getPropert

我正在尝试开发一个动态用户界面。当用户单击某个指示器时,该指示器的图形将与一些操作按钮一起实例化。请参见图中的示例。图形与按钮一起在HBox中创建,然后添加到VBox中。我无法解决的问题是:单击按钮时,如何访问相应的元素

问题简单地归结为:

  Button buttonRemove = new Button ();
  buttonRemove.setMinWidth (80);
  buttonRemove.setText ("Remove");
  buttonMap.getProperties ().put ("--IndicatorRemoveButton", indicator.getName ());
  buttonRemove.setOnAction (e -> buttonRemoveClick ());

   private Object buttonRemoveClick ()
   {
      // Which button clicked me??

      return null;
   } /*** buttonRemoveClick ***/
任何帮助都将不胜感激。我有点受不了了


可以将参数传递给lambda中的
按钮RemoveClick
方法,只要它是有效的final或参数

private void buttonRemoveClick (HBox group) {...}

在这种情况下,您还可以传递
ActionEvent
,并获取源代码以检索
按钮
;这可能不足以删除元素,但为此,您可以遍历父元素,直到到达
HBox的子元素

private void buttonRemoveClick (ActionEvent event) {
    Node currentNode = (Node) event.getSource(); // this is the button

    // traverse to HBox of container
    Node p;
    while ((p = currentNode.getParent()) != containerVBox) {
        currentNode = p;
    }
    // remove part including the Button from container
    containerVBox.getChildren().remove(currentNode);
}

动态创建按钮后,在代码中添加button.setOnAction事件处理程序。正如您在代码中看到的,这就是我现在所做的。你的意思是我必须做一些与我现在所做的不同的事情吗?你说元素是什么意思?你想知道是哪个按钮点击了吗?你想在按钮点击时删除图形吗?你救了我一天!我用了你的第二种方法,效果很好。当创建包含按钮的HBox时,我在属性中为按钮提供信息以识别它。我以前看过这个解决方案的描述,但无法让它工作,所以非常感谢您的清晰描述!
private void buttonRemoveClick (ActionEvent event) {
    Node currentNode = (Node) event.getSource(); // this is the button

    // traverse to HBox of container
    Node p;
    while ((p = currentNode.getParent()) != containerVBox) {
        currentNode = p;
    }
    // remove part including the Button from container
    containerVBox.getChildren().remove(currentNode);
}
buttonRemove.setOnAction (this::buttonRemoveClick);