如何在javafx 8中多次使用控件?
作者:互联网
我目前正在使用javafx 8,并在一个简单的解决方案中提出了以下问题:
我有不同的控件(按钮),将出现
>在主要内容(窗格的中心)中
>在页脚中(窗格底部)
Button one = new Button("1");
Button two = new Button("2");
Button three = new Button("3");
VBox vbox = new VBox();
vbox.getChildren().addAll(one, two, three);
HBox hbox = new HBox();
hbox.getChildren().addAll(two, three); //To clarify my problem i leave one node in vbox
现在看来,最后一个.addAll()会删除另一个框中的引用.
BorderPane root = new BorderPane();
root.setCenter(vbox);
root.setBottom(hbox);
输出:
我尝试(用于测试)简单地重用按钮,但是:
root.setCenter(one);
root.setBottom(one);
结果是
java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.RuntimeException: Exception in Application start method
...
Caused by: java.lang.IllegalArgumentException: Children: duplicate children added: parent = BorderPane@1784a61
那使我考虑以下问题:
>除了创建新的按钮实例之外,是否有其他方法可以解决该问题?
> HBox和VBox节点会怎样?
>为什么不能重复使用控件?
解决方法:
如Node
类的JavaDocs中所述:
A node may occur at most once anywhere in the scene graph.
Specifically, a node must appear no more than once in all of the
following: as the root node of aScene
, the childrenObservableList
of
aParent
, or as the clip of aNode
.If a program adds a child node to a
Parent
(includingGroup
,Region
,
etc.) and that node is already a child of a differentParent
or the
root of aScene
, the node is automatically (and silently) removed from
its former parent.
因此,您无法做您想做的事情.一个按钮只能显示一次,您不能在两个位置显示相同的按钮.为了更清楚地说明-例如如果您能够在两个地方具有相同的实例,则getParent()方法返回?没什么,这是不可能的.一个实例只能在一个地方存在.
如果要重复使用该按钮,则必须将其复制.
标签:java,javafx-8 来源: https://codeday.me/bug/20191011/1889165.html