我想在javaFX 2中创建一个应用程序,该应用程序以较小的登录窗口打开,然后,当您输入正确的数据时,它会将您带到更大的主窗口。两者都是用 fxml 设计的,事件在 java 代码中处理。
是的,我知道,它与示例中的应用程序几乎相同,我尝试做我想做的事,它在那里工作。
现在,当我在我的项目中做同样的事情时,当我想改变舞台的值时,我遇到了一个问题。
正如您在下面的代码中看到的,我有全局变量,我将启动方法中的 primaryStage 的值设置为它。作为测试,我在启动方法结束时将其打印出来并设置值。
然后,当我尝试在单击按钮(方法按钮单击)时使用它时,阶段变量的值为 null,因此我不能使用它来调整窗口大小或其他任何东西。
我的问题是,尽管我不在两次打印之间使用更改任何内容,但为什么会重置舞台变量值?
这段代码是我尝试过的示例,我只是删除了所有代码,这对于理解我的应用程序如何工作并不重要。
public class App extends Application {
private Stage stage;
@FXML
private AnchorPane pane;
@Override
public void start(Stage primaryStage) {
try {
stage = primaryStage; // Set the value of primaryStage to stage
primaryStage.setScene(new Scene(openScene("Login"))); // Load Login window
primaryStage.show(); // Show the scene
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(stage);// <-- Here it has the value of primaryStage obviously
}
@FXML
void buttonClick(ActionEvent event) throws IOException {
// Note that even if I try to print here, the value of stage is still
// null, so the code doesn't affect it
// Also, this loads what I want, I just can't change the size.
try{
pane.getChildren().clear(); // Clear currently displayed content
pane.getChildren().add(openScene("MainScene")); // Display new content
System.out.println(stage); // <-- Here, output is null, but I don't know why
stage.setWidth(500); // This line throws error because stage = null
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Parent openScene(String name) throws IOException {
//Code from FXML login example
Parent parent = (Parent) FXMLLoader.load(PrijavnoOkno.class.getResource(name
+ ".fxml"), null, new JavaFXBuilderFactory());
return parent;
}
public static void main(String[] args) {
launch(args);
}
}
虽然不清楚按钮单击操作方法由谁以及在哪里调用,但我按下它是登录按钮在Login.fxml
的操作。另外,我假设您已将App
(又名PrijavnoOkno
)定义为此Login.fxml的控制器。
根据这些假设,有 2 个 App.class 实例:
一个在应用程序启动时创建,并且在 start()
方法中为阶段变量分配了主阶段,
以及由FXMLLoader创建的另一个实例(加载Login.fxml时),其中未分配阶段变量,因此未分配NPE。
正确的方法之一是,为 Login.fxml 创建一个新的控制器类,在其中调用您的登录操作。从那里访问全局舞台(通过在应用程序中将其设置为静态)。