启动JavaFX应用程序时,将创建应用程序类的一个实例,并且(在其他情况下)
start()
方法调用
Application
FX应用程序线程上的实例。
加载FXML文件时,如果FXML文件指定了控制器类,则会创建该控制器类的实例
@FXML
-注释字段被注入到该实例中
initialize()
方法被调用。所有这些都发生在调用
FXMLLoader.load()
.
因此,在代码中,您最终会得到
MainWindow
. 这个
开始()
方法在一个实例上调用,该实例初始化
mainWindow
字段,以及
初始化()
方法在另一个实例上调用。自从
主窗口
在第二个实例中从未初始化,当您尝试在
初始化()
方法
将控制器类与
应用
班这个
应用
类只应作为一个整体管理应用程序的生命周期(通常,它应实现启动应用程序所需的代码):
package projecterror.controller;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class MainWindow extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Test Project");
initMainWindow(primaryStage);
}
public void initMainWindow(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../view/MainWindow.fxml"));
BorderPane mainWindow = loader.load();
Scene scene = new Scene(mainWindow);
primaryStage.setScene(scene);
//Fullscreen
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
primaryStage.setX(bounds.getMinX());
primaryStage.setY(bounds.getMinY());
primaryStage.setWidth(bounds.getWidth());
primaryStage.setHeight(bounds.getHeight());
primaryStage.setResizable(false);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package projecterror.controller;
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
public class MainWindowController {
@FXML
private BorderPane mainWindow;
@FXML
Menu menuFile, menuAnalysis;
@FXML
MenuItem menuNew;
@FXML
private void initialize() {
menuNew.setOnAction((event) -> {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../view/AnchorTest.fxml"));
AnchorPane anchorTest = (AnchorPane) loader.load();
mainWindow.setCenter(anchorTest);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
以便控制器访问
BorderPane
,您需要从FXML注入它(注意上面控制器代码中的注释)。添加
fx:id
到FXML文件中的元素:
<BorderPane style="-fx-background-color: #DCDCDC;" fx:id="mainWindow"
xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="projecterror.controller.MainWindowController">