Enter Key Event Is Not Working On Dialog In Javafx?

后端 未结 4 1070
情话喂你
情话喂你 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:37

    Here how i solved it. it works fine below is my confirm alert function.

    public static boolean confirmAlert(String title, String msg){
    
            ButtonType buttonTypeYes = new ButtonType("Yes", ButtonBar.ButtonData.OK_DONE);
            ButtonType buttonTypeNo = new ButtonType("No",ButtonBar.ButtonData.CANCEL_CLOSE);
    
            Alert alert = new Alert(Alert.AlertType.NONE, msg,buttonTypeNo,buttonTypeYes);
            alert.setTitle(title);
    
            Button button1 = (Button) alert.getDialogPane().lookupButton(buttonTypeYes);
            button1.setDefaultButton(false); //***set default to false***
    
            Button button2 = (Button) alert.getDialogPane().lookupButton(buttonTypeNo);
    
            button1.setOnKeyReleased(event -> {
                if(event.getCode() == KeyCode.ENTER)
                    alert.setResult(buttonTypeYes);
            });
            button2.setOnKeyReleased(event -> {
                if(event.getCode() == KeyCode.ENTER)
                    alert.setResult(buttonTypeNo);
            });
            alert.showAndWait();
            return alert.getResult()==buttonTypeYes;
        }
    

提交回复
热议问题