javafx.scene.layout.Pane无法强制转换为javafx.fxml.FXMLLoader [英] javafx.scene.layout.Pane cannot be cast to javafx.fxml.FXMLLoader
问题描述
我在尝试从场景切换到另一个场景时遇到了麻烦。情况如下:
I'm having trouble when trying to switch from a scene to another scene. The scenario is this:
当前视图和控制器: login.fxml
和 LoginController
下一步查看和控制器: loggedWindow.fxml
和 UserPanelController
。
现在,我在 LoginController
并尝试将场景切换为 loggedWindow.fxml
发送到 UserPanelController
一个参数,但当我使用我的代码时,我得到:
Now, I'm in LoginController
and trying to switch the scene to loggedWindow.fxml
sending to UserPanelController
a parameter, but when I'm using my code I get:
javafx.scene.layout.Pane cannot be cast to javafx.fxml.FXMLLoader
LoginController:
LoginController:
FXMLLoader loggedWindow = null;
loggedWindow = FXMLLoader.load(getClass().getResource("loggedWindow.fxml")); // here crashes!
Pane root = loggedWindow.load();
UserPanelController controller = loggedWindow.getController();
controller.initData(customer);
Stage switchScene = (Stage)((Node)event.getSource()).getScene().getWindow();
switchScene.setResizable(false);
switchScene.setTitle("Welcome " + customer.FirstName + " " + customer.LastName);
switchScene.setScene(new Scene(root, 800, 500));
switchScene.show();
LoggedWindow.fxml
LoggedWindow.fxml
<Pane maxHeight="500.0" maxWidth="800.0" minHeight="500.0" minWidth="800.0" prefHeight="500.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Main.UserPanelController">
<children>
<ToolBar prefHeight="40.0" prefWidth="831.0">
<items>
.
.
stuff (buttons/labels and so on).
.
.
</Pane>
我将不胜感激任何帮助!提前致谢。
I would appreciate any help! Thanks in advance.
还考虑了这个参考:访问FXML控制器类
推荐答案
您正在使用FXMLLoader的load方法,该方法返回.fxml文件的根节点。在这种情况下,它会返回您的窗格。
You're using the "load" method of FXMLLoader which returns the root node of your .fxml file. In that case, it's returning your Pane.
您应该使用它来创建场景!
You should use it to create your scene!
查看JavaFX教程中给出的示例,如:
See the example given in the JavaFX tutorial, like:
Pane root = FXMLLoader.load(getClass().getResource("loggedWindow.fxml"));
Scene scene = new Scene(root, width, height, color);
其他方式,取自我的一个旧代码,使用非静态FXMLLoader:
Other way, taken from one of my old code, using non-static FXMLLoader:
FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlFile));
Parent root;
try {
root = loader.load();
} catch (IOException ioe) {
// log exception
return;
}
// Color.TRANSPARENT allows use of rgba colors (alpha layer)
setScene(new Scene(root, Color.TRANSPARENT));
这篇关于javafx.scene.layout.Pane无法强制转换为javafx.fxml.FXMLLoader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!