如何将自定义 Pane 添加到该代码中的自定义场景?
public class MainScene extends Scene {
public MainScene() {
super(new FlowPane(), 800, 600);
}
public void addItem(String name) {
Item item = new Item(name); // Item extends Pane.
getRoot().getChildren().add(item); // That obviously doesn't work.
}
}
最佳答案
在您的示例中,您没有对根元素的引用。
由于使用了 super()
,因此在不向用户询问的情况下,您无法传递根元素的引用。
由于 getRoot()
返回一个 Parent,因此出于显而易见的原因,您不能对其使用 getChildren()
。
您可以做的是将 getRoot()
类型转换为 FlowPane
。
public void addItem(String name) {
Pane item = new Pane(); // Item extends Pane.
((FlowPane)getRoot()).getChildren().add(item);
}
关于java - 将节点添加到扩展场景的类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33051893/