Enter Key Event Is Not Working On Dialog In Javafx?

后端 未结 4 1069
情话喂你
情话喂你 2020-12-21 17:27

I have tried the below code, it works fine with mouse event, but when I use key event i.e ENTER Key on any button than its not showing the result.

Alert aler         


        
4条回答
  •  醉梦人生
    2020-12-21 17:51

    I don't know if this is not a kind of too much of a workaround, but at least it works:

     import javafx.event.EventHandler;
     import javafx.scene.control.Button;
     import javafx.scene.input.KeyCode;
     import javafx.scene.input.KeyEvent;
    
         [...]
    ButtonType buttonTypeTwo = new ButtonType("Two");
    ButtonType buttonTypeThree = new ButtonType("Three");
    
    alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeThree);
    
    //Create a button for every ButtonType you add to your alert and give it a Eventhandler 
    Button button1 = (Button) alert.getDialogPane().lookupButton(buttonTypeOne);
    Button button2 = (Button) alert.getDialogPane().lookupButton(buttonTypeTwo);
    Button button3 = (Button) alert.getDialogPane().lookupButton(buttonTypeThree);
    
    
    button1.setOnKeyReleased(new EventHandler() {
        @Override
        public void handle(KeyEvent event) {
            if(event.getCode() == KeyCode.ENTER)
        alert.setResult(buttonTypeOne);     
        }
    });
    button2.setOnKeyReleased(new EventHandler() {
        @Override
        public void handle(KeyEvent event) {
            if(event.getCode() == KeyCode.ENTER)
        alert.setResult(buttonTypeTwo);     
        }
    });
    button3.setOnKeyReleased(new EventHandler() {
        @Override
        public void handle(KeyEvent event) {
            if(event.getCode() == KeyCode.ENTER)
        alert.setResult(buttonTypeThree);       
        }
    });
     //go ahead with your code
    Optional result = alert.showAndWait();
    [...]
    

    You just create some Buttons and assigned them the actual buttons on your alert. In the next Step you can give every button an EventHandler which just (In this example) checks - when any key is released - if the key was ENTER and set the result.

    I guess there are better solutions for this. But it's the easiest way which comes to my mind currently. Hope it helps you.

提交回复
热议问题