当我尝试在初始化时将我的阶段设置为变量时,我不断收到null
引用异常。
我的代码。
public class ListController implements Initializable {
private Stage thisStage;
@Override
public void initialize(URL location, ResourceBundle resources) {
lblCount.setText("Hey"); //This works
thisStage = (Stage) lblCount.getScene().getWindow(); //this doesn't
}
public ListController()
{
thisStage = (Stage) lblCount.getScene().getWindow(); //this doesn't
}
}
我尝试使用构造函数,但两者都不起作用。
答案 0 :(得分:0)
获取舞台引用的一种方法是在控制器上创建一个方法并进行设置:
FXMLLoader loader = new FXMLLoader();
Parent node = loader.load(getClass().getResource("view.fxml").openStream());
Scene scene = new Scene(node);
Stage stage = new Stage();
Controller controller = (Controller)loader.getController();
controller.setPrimaryStage(stage);
stage.show();
然后在你的方法中你有一个有效的参考。
答案 1 :(得分:0)
当您调用舞台时,您可以通过类似
的方法传递舞台参考 Stage primaryStage = new Stage();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(YourClass.class.getResource("yourpaht.fxml"));
//here you change AnchorPane for your root Node
rootLayout = (AnchorPane) loader.load();
// Show scene.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// Da acceso al programa principal.
ListController controller = loader.getController();
//method for passing the stage to the controller
controller.controlerPassing(this, primaryStage);
// Show stage,
primaryStage.show();
现在控制器类看起来像这样
public class ListController implements Initializable {
private Stage stage;
pivate YourClass classs;
public controlerPassing(YourClass classs, Stage stage){
this.stage = stage;
this.classs = classs;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
lblCount.setText("Hey"); //This works
//now you can do whatever you want whit the stage
stage. do stuff........
}
}
答案 2 :(得分:-1)
如果我们在Stage类中找到数据类型并相应地使用这样的初始化,就可以解决这个空引用。
例如,
Stage myStage = null ; // this will raise a null pointer reference exception the possible solution can be to say:
Stage myStage = {" ", 0, ' ', etc } ; // as long as the class Stage has data members like String, int, char, etc