2017-04-02 90 views
0

我正在尝试开发一个动态用户界面。当用户点击某个指标时,它的图形会与一些操纵按钮一起实例化。看到图像的例子。该图形在HBox中与按钮一起创建,然后添加到VBox中。我无法解决的问题是:单击按钮时,如何访问相应的元素?如何访问动态用户界面中的GUI元素

的问题简单地归结为:

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 ***/ 

任何帮助将不胜感激。我有点卡住了。

Example of dynamic interface

+0

一个孩子在你的代码动态创建按钮后,你可以穿越到父,加button.setOnAction事件处理程序。 – Sedrick

+0

这就是我现在所做的,正如你在代码中看到的那样。你的意思是我必须做一些与我现在所做的不同的事情吗? – Arnold

+0

当你说元素时,你是什么意思? – Sedrick

回答

1

只要它是有效的最终参数或参数,就可以将参数传递给lambda表中的buttonRemoveClick方法。

private void buttonRemoveClick (HBox group) {...} 
buttonRemove.setOnAction (e -> buttonRemoveClick (theGroup)); 

在这种情况下,你也可以通过ActionEvent并获得源检索Button;这可能是不够的要删除的元素,但对于这一点,直到你到达的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); 
+0

你救了我的一天!我用你的第二种方法,这很好。当创建包含按钮的HBox时,我会在属性中提供信息给按钮以标识它。我看到之前描述过的这个解决方案,但无法运行,所以非常感谢您的明确描述! – Arnold