JavaFX - getScene()返回null [英] JavaFX - getScene() returns null
问题描述
我刚开始使用JavaFX Scene Builder来构建一个小应用程序。
I just started using JavaFX Scene Builder to build a small application.
它由一个属于'login的控制器类'Login.java'组成。 fxml',其中FXML文件'registrierung.fxml'通过名为'registrationClicked(ActionEvent event)'的方法加载:
It is made up of a controller class 'Login.java' which belongs to 'login.fxml', in which the FXML file 'registrierung.fxml' is loaded via a method called 'registrationClicked(ActionEvent event)':
public class Login {
@FXML
private void registrationClicked(ActionEvent event){
try{
((Node) (event.getSource())).getScene().getWindow().hide();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/fxml/registrierung.fxml"));
Parent root = (Parent) loader.load();
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setTitle("Registration");
stage.setScene(scene);
stage.setResizable(false);
stage.show();
} catch(IOException e){
e.printStackTrace();
}
}
现在我想获得对阶段的引用控制器类'Registrierung.java'中的'registrierung.fxml'通过根节点vboxRoot:
Now I want to get a reference to the stage of 'registrierung.fxml' in the controller class 'Registrierung.java' via the root node vboxRoot:
@FXML
private VBox vboxRoot;
Stage stage = (Stage) vboxRoot.getScene().getWindow();
但是'getScene()'总是会导致NullPointerException。 FXML文件的控制器类在Scene Builder中调整。
However 'getScene()' always leads to a NullPointerException. The controller classes for both FXML files are adjusted in Scene Builder.
这是我在'registrierung.fxml'中设置rood节点的方式:
This is how I set up the rood node in 'registrierung.fxml':
<VBox fx:id="vboxRoot" maxHeight="-Infinity" maxWidth="-Infinity" prefHeight="267.0" prefWidth="355.0" stylesheets="@../css/styles.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="businesslogik.Registrierung">
我做错了什么?
推荐答案
您正在尝试获取尚未初始化的对象的场景。
you are trying to get the scene for an object that has not been initialized yet. if you were doing the same operation in
@Override
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
Stage stage = (Stage) vboxRoot.getScene().getWindow();
}
或者如果你有点击某事后触发的事件(后执行)场景已加载)
or if you have an event that triggers once you click something (which executes after the scene has loaded)
@FXML
private void action(ActionEvent event) throws IOException {
Stage stage = (Stage) vboxRoot.getScene().getWindow();
}
这样可行!
这篇关于JavaFX - getScene()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!