【发布时间】:2016-01-19 09:58:37
【问题描述】:
我最初的 fxml(比如home.fxml)有很多功能,因此需要很长时间才能完全加载。因此,为了避免程序启动和 fxml 加载之间的时间间隔,我引入了一个带有 gif 图像的 fxml(比如loader.fxml),该图像应该在主 fxml 加载时出现。
问题是我的 loader.fxml 中的 gif 图像没有移动,因为程序挂起,直到 home.fxml 完全加载。
为了避免这种情况,我将 home.fxml 加载移动到一个线程中,如下面的代码所示。
public class UATReportGeneration extends Application {
private static Stage mainStage;
@Override
public void start(Stage stage) {
Parent loaderRoot = null;
try {
loaderRoot = FXMLLoader.load(getClass().getResource("/uatreportgeneration/fxml/Loader.fxml"));
} catch (IOException ex) {
Logger.getLogger(UATReportGeneration.class.getName()).log(Level.SEVERE, null, ex);
}
Scene loadScene = new Scene(loaderRoot);
stage.setScene(loadScene);
stage.initStyle(StageStyle.UNDECORATED);
stage.getIcons().add(new Image(this.getClass().getResourceAsStream("/uatreportgeneration/Images/logo.png")));
stage.show();
mainStage = new Stage(StageStyle.UNDECORATED);
mainStage.setTitle("Upgrade Analysis");
mainStage.getIcons().add(new Image(this.getClass().getResourceAsStream("/uatreportgeneration/Images/logo.png")));
setStage(mainStage);
new Thread(() -> {
Platform.runLater(() -> {
try {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("/uatreportgeneration/fxml/Home.fxml"));
Scene scene = new Scene(root);
mainStage.setScene(scene);
mainStage.show();
stage.hide();
System.out.println("Stage showing");
// Get current screen of the stage
ObservableList<Screen> screens = Screen.getScreensForRectangle(new Rectangle2D(mainStage.getX(), mainStage.getY(), mainStage.getWidth(), mainStage.getHeight()));
// Change stage properties
Rectangle2D bounds = screens.get(0).getVisualBounds();
mainStage.setX(bounds.getMinX());
mainStage.setY(bounds.getMinY());
mainStage.setWidth(bounds.getWidth());
mainStage.setHeight(bounds.getHeight());
System.out.println("thread complete");
} catch (IOException ex) {
Logger.getLogger(UATReportGeneration.class.getName()).log(Level.SEVERE, null, ex);
}
});
}).start();
}
public static Stage getStage() {
return mainStage;
}
public static void setStage(Stage stage) {
mainStage = stage;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
但是在这段代码之后,我的程序也挂了(gif 图像没有移动)。如果我在 Platform.runLater() 之外加载 fxml,我会收到异常 Not on FX Thread。
我也厌倦了使用Task(),但是如果我尝试在Platform.runLater()之外加载fxml,gif图像正在移动但fxml没有在后台加载。
谁能帮助我并告诉我如何更正代码,以便我的 fxml 在后台加载而不会干扰前台进程。
【问题讨论】:
标签: javafx task fxml fxmlloader