JavaFX 2.0 + FXML - 奇怪的查找行为

标签 java javafx-2 fxml

感谢 Node#lookup(),我想在使用 FXMLLoader 加载的场景中找到 VBox 节点,但我得到以下异常:

java.lang.ClassCastException: com.sun.javafx.scene.control.skin.SplitPaneSkin$Content 无法转换为 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

提前致谢

最佳答案

获取 VBox 引用的最简单方法是调用 FXMLLoader#getNamespace()。例如:

VBox myvbox = (VBox)fxmlLoader.getNamespace().get("myvbox");

请注意,您需要创建一个 FXMLLoader 实例并调用非静态版本的 load() 才能使其正常工作:

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("test.fxml"));
AnchorPane page = (AnchorPane) fxmlLoader.load();

关于JavaFX 2.0 + FXML - 奇怪的查找行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12324799/

相关文章:

java - 需要提交多少次调用才能与 newWorkStealingPool 一起使用?

java - 你会在 MySQL 中映射 Java/Hibernate 中的 BigDecimal 什么类型?

java - okHttpClient 响应给出垃圾值

javafx如何使用FXML从tableview中获取选定的数据

mouseevent - 如何为Tableview中表格列的单元格设置点击事件?

java - 无法正确创建二叉树?

css - JavaFX2 : can I set opacity for Nodes' content and stroke separately?

JavaFX : can controller be an abstract class?

javafx-2 - 如何设置 JavaFX 2 全屏消息的样式?

java - 循环遍历 FXML 元素并将其中一些元素添加到列表时遇到问题