JavaFX 全屏切换场景

标签 java javafx fullscreen fxml

我想使用“下一步”按钮在全屏模式下切换我的 JavaFX 应用程序的场景。但是,如果我单击该按钮,它会在一秒钟内从全屏切换到窗口,然后再切换回全屏。我怎样才能避免这种情况并保持全屏模式?

一些相关的片段:

应用程序.java:

public class Application extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLMain.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
        stage.setFullScreen(true);
        stage.setTitle("AppName");

    }

    public static void main(String[] args) {
        launch(args);
    }

}

FXMLMainController.java:

@FXML
private void handleBtnNext(ActionEvent event) throws Exception{
    Stage stage; 
    Parent root;
    if(event.getSource()==btnNext){
        //get reference to the button's stage         
        stage=(Stage) btnNext.getScene().getWindow();
        //load up OTHER FXML document
        root = FXMLLoader.load(getClass().getResource("FXMLOptions.fxml"));
    }
    else{
        stage=(Stage) btnNext.getScene().getWindow();
        root = FXMLLoader.load(getClass().getResource("FXMLMain.fxml"));

    }
    //create a new scene with root and set the stage
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
    stage.setFullScreen(true);
}

最佳答案

当您切换场景时,应用程序会退出全屏模式,这种行为很奇怪(我在 Java 8u60、OS X 10.11.3 上也遇到过这种情况)。它可能是 bug .

要解决它,您可以重复使用相同的舞台和场景并调整场景的根,而不是更改场景本身。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class FullScreenScenes extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        Button next1 = new Button("Show Scene 2");
        StackPane layout1 = new StackPane(next1);
        layout1.setStyle("-fx-background-color: palegreen;");

        Button next2 = new Button("Show Scene 1");
        StackPane layout2 = new StackPane(next2);
        layout2.setStyle("-fx-background-color: paleturquoise;");

        Scene scene = new Scene(layout1);

        next1.setOnAction(event -> scene.setRoot(layout2));
        next2.setOnAction(event -> scene.setRoot(layout1));

        stage.setScene(scene);
        stage.setFullScreen(true);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

关于JavaFX 全屏切换场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026764/

相关文章:

java - 我需要锁吗?

java - 覆盖 VideoView 但保持对 Android 底层 Activity 的关注

Java Logger 对象不附加到日志文件

java - ListChangeListener wasPermutated block

java - ReadOnlyBooleanWrapper : incorrect behaviour when used with Bindings. 或

opengl - X11 全屏窗口 (OpenGL)

ios - 当用户尝试全屏播放时,MPMoviePlayerController 停止并重置电影 [iOS]

javascript - 在 Apple 设备上请求 HTML5 视频全屏

java - LibGDX 写入文本文件并收到各种错误

java - 避免不在 FX 应用程序线程上导致 UI 崩溃