JavaFx ScrollPaneSkin 无法转换为 ScrollPane

JavaFx ScrollPaneSkin cannot be cast to ScrollPane

最近我在研究JavaFx,我想做一些复杂的设计布局。设计理念是当我点击一个按钮时 AnchorPane 动态加载 ScrollPane


这是我的代码

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/rahadur/view/FXMLDocument.fxml"));
        AnchorPane pane = (AnchorPane)loader.load();

         /* HERE IS THE PROBLEM FAILD TO CONVERT SCROLLPANE */
        ScrollPane scroll_pane = (ScrollPane) btn_add_click.getParent().getParent();

        Node node = scroll_pane.getContent();
        node = null;
        scroll_pane.setContent(pane);

问题是,当代码试图从父 Class 中隐藏 ScrollPane 时,它向我展示了这个 Error

java.lang.ClassCastException: com.sun.javafx.scene.control.skin.ScrollPaneSkin cannot be cast to javafx.scene.control.ScrollPane

我搜索了很多次,但没有找到解决这个问题的方法。希望大家给我一个连击解决方案

感谢您审阅此问题...

结合getChildren()getParent()的方法遍历场景图并不是那么可靠和合适。给一些最常用的节点 fx:id 并通过 lookup() :

获取它们

在 fxml 文件中

<ScrollPane fx:id="scrollpane"  ... >

在后台class

ScrollPane scroll_pane = (ScrollPane) scene.lookup("#scrollpane");
scroll_pane.setContent(anchorpane);