JavaFX 2.0 + FXML - 奇怪的查找行为 [英] JavaFX 2.0 + FXML - strange lookup behaviour

查看:191
本文介绍了JavaFX 2.0 + FXML - 奇怪的查找行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在装有 FXMLoader 的场景中找到一个VBox节点,这要归功于 Node#lookup()但是我得到以下异常:

I want to find a VBox node in a scene loaded with FXMLoader thanks to Node#lookup() but I get the following exception :

java.lang.ClassCastException:com.sun.javafx.scene.control.skin.SplitPaneSkin $ Content not not be转发给javafx.scene.layout.VBox

代码:

public class Main extends Application {  
    public static void main(String[] args) {
        Application.launch(Main.class, (java.lang.String[]) null);
    }
    @Override
    public void start(Stage stage) throws Exception {
        AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("test.fxml"));
        Scene scene = new Scene(page);
        stage.setScene(scene);
        stage.show();

        VBox myvbox = (VBox) page.lookup("#myvbox");
        myvbox.getChildren().add(new Button("Hello world !!!"));
    }
}

fxml文件:

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" >
  <children>
    <SplitPane dividerPositions="0.5" focusTraversable="true" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
      <items>
        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
        <VBox fx:id="myvbox" prefHeight="398.0" prefWidth="421.0" />
      </items>
    </SplitPane>
  </children>
</AnchorPane>

我想知道:

1.为什么查找方法返回 SplitPaneSkin $ Content 而不是 VBox

2.如何获得 VBox 以另一种方式?

I would like to know :
1. Why lookup method return a SplitPaneSkin$Content and not a VBox ?
2. How I can get the VBox in another manner ?

提前致谢

推荐答案


  1. SplitPane将所有项目放在单独的堆栈窗格中(想象为 SplitPaneSkin $ Content )。由于未知原因,FXMLLoader为它们分配与root child相同的id。您可以通过下一个实用方法获得所需的VBox:

  1. SplitPane puts all items in separate stack panes (fancied as SplitPaneSkin$Content). For unknown reason FXMLLoader assign them the same id as root child. You can get VBox you need by next utility method:

public <T> T lookup(Node parent, String id, Class<T> clazz) {
    for (Node node : parent.lookupAll(id)) {
        if (node.getClass().isAssignableFrom(clazz)) {
            return (T)node;
        }
    }
    throw new IllegalArgumentException("Parent " + parent + " doesn't contain node with id " + id);
}

并使用下一个方式:

VBox myvbox = lookup(page, "#myvbox", VBox.class);
myvbox.getChildren().add(new Button("Hello world !!!"));


  • 你可以使用控制器并添加自动填充字段:

  • you can use Controller and add autopopulated field:

    @FXML
    VBox myvbox;
    


  • 这篇关于JavaFX 2.0 + FXML - 奇怪的查找行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆