Search code examples
javafxcheckboxkeyevent

javafx checkbox clicked while key pressed will not change state


I have a very simple problem, which I can't find in any other posts :

In javafx15 / java15.0.1, I am trying to click a Checkbox while pressing, for example, the CONTROL key... State is not changing.

I tried to catch the key (with a key event on the checkbox), and I do catch the control key pressed... But state of checkbox just does not change if a key is pressed simultaniously.

How to get this to just work in a transparent way ?

Here is a most basic simple code to illustate the problem :

package checkboxkeypressed;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.stage.Stage;

public class CheckboxWhileKeyPressedNotWorking extends Application {

    private CheckBox checkbox = new CheckBox();

    @Override
    public void start(Stage primaryStage) {
        checkbox.setText("Click me while pressing a key...");
        Scene scene = new Scene(checkbox, 200, 50);

        primaryStage.setTitle("Checkbox cannot be ticked while a key is pressed !!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

Any help would be greatly appreciated.


Solution

  • Improving on the solution offered by etuygar:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.CheckBox;
    import javafx.stage.Stage;
    
    public class CheckboxWhileKeyPressedNotWorking extends Application {
    
        private final CheckBox checkbox = new CheckBox();
        private boolean isControlKeyDown = false;
    
        @Override
        public void start(Stage primaryStage) {
    
            checkbox.setText("Click me while pressing <CNTRL> key");
            checkbox.setOnMouseClicked(e->{
                if(isControlKeyDown){
                    checkbox.fire(); //change check box state
                }
            });
    
            Scene scene = new Scene(checkbox, 300, 50);
            scene.setOnKeyPressed(keyEvent -> {
                isControlKeyDown = keyEvent.isControlDown();
            });
    
            scene.setOnKeyReleased(keyEvent -> {
                isControlKeyDown = keyEvent.isControlDown();
            });
    
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }