Search code examples
javajavafxfullscreentextfield

JavaFX program toggles full-screen when enter key is pressed inside of a TextField


I made my program enter full-screen whenever both of the keyboard keys, alt and enter, are pressed at the same time. This mostly works as expected.

The issue is that my program will toggle full-screen mode whenever the enter key is pressed. It doesn't matter if the alt key is pressed.

How can I make it so that the program will not toggle full-screen mode when only the enter key is pressed.

I am using OpenJFX 11.

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;


public class Main extends Application {
   final KeyCombination FullScreenKeyCombo = 
         new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_ANY);

    @Override
    public void start(Stage stage) {
            GridPane grid = new GridPane();
            Scene scene = new Scene(grid, 1600, 900);
            stage.setScene(scene);
            stage.show();

         // create TextField and add to GridPane
         TextField textField = new TextField();
         grid.add(textField, 0, 0);

         // toggle full-screen when alt + enter is pressed
         scene.addEventHandler(KeyEvent.KEY_PRESSED, event -> {

            if(FullScreenKeyCombo.match(event)) {

               stage.setFullScreen(!stage.isFullScreen());

            }
         });

    }

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

Solution

  • In this line:

    new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_ANY);
    

    ALT_ANY means “I don’t care if the Alt key is pressed or not.”

    Use ALT_DOWN instead:

    new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_DOWN);