Arpit Rajput
Arpit Rajput

Reputation: 21

Toggle full screen feature using F11 key in JavaFX

How would you implement a full screen feature that can be toggled by pressing F11?

Upvotes: 2

Views: 726

Answers (1)

Sunflame
Sunflame

Reputation: 3186

You can add an EventHandler to the primaryStage where you specify the functionality like:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("View.fxml"));
        AnchorPane pane = loader.load();
        primaryStage.setScene(new Scene(pane, 400, 400));
        primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
            if (KeyCode.F11.equals(event.getCode())) {
                primaryStage.setFullScreen(!primaryStage.isFullScreen());
            }
        });
        primaryStage.show();
    }
}

Just to be complete: View.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="stackoverflow.testfullscreen.Controller">

</AnchorPane>

Controller:

public class Controller implements Initializable {

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

}

I didn't implement a webview, but it should work with any scene.

Upvotes: 5

Related Questions