Java JOptionPane.showConfirmDialog hot key

冷暖自知 提交于 2019-12-10 17:25:29

问题


I am displaying a confirmation dialog in Java using JOptionPane.showConfirmDialog. The dialog shows a Yes No confirmation to the user. This is called as follows:

int result = JOptionPane.showConfirmDialog(sessionObjects.getActiveComponent(), 
                 "Are you sure you want to exit?", "My App", JOptionPane.YES_NO_OPTION);

The question is as this is a simple confirmation, can the user press y for yes and n for no? At present the user has to click on the buttons?

Thanks,

Andez


回答1:


You already have "hotkeys" (mnemonics) for the buttons: Alt+Y for "Yes" and Alt+N for "No".

You can also hit Tab to toggle between them and Space to press.




回答2:


There is another simpler possibility: you can press alt in a program and then release it in a same way:

public static void pressAlt(){
    try {
        Robot r = new Robot();
        r.keyPress(KeyEvent.VK_ALT);
    } catch (AWTException ex) {
        Logger.getLogger(ManualDetection.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static void releaseAlt(){
    try {
        Robot r = new Robot();
        r.keyRelease(KeyEvent.VK_ALT);
    } catch (AWTException ex) {
        Logger.getLogger(ManualDetection.class.getName()).log(Level.SEVERE, null, ex);
    }
}

then when you call:

 pressAlt();
 int confirm = JOptionPane.showConfirmDialog(... bla bla bla ... 
                                                  ,JOptionPane.YES_NO_OPTION);
 releaseAlt();

the behavior is exactly the same, as you desired...




回答3:


No, but you can create your own JDialog that could do that.




回答4:


Look at Stopping Automatic Dialog Closing



来源:https://stackoverflow.com/questions/4793266/java-joptionpane-showconfirmdialog-hot-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!