4

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

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Andez
  • 5,588
  • 20
  • 75
  • 116

4 Answers4

7

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...

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
v.mic
  • 71
  • 1
  • 1
2

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.

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • Thanks. I guess I can live with this for now. – Andez Jan 25 '11 at 12:42
  • i don't believe mnemonics currently work for buttons a Mac. (Java 10). Even if you run ButtonDemo.java from the [tutorial](https://docs.oracle.com/javase/tutorial/uiswing/components/button.html), the alt key highlights the mnemonic visually, but does not work to actually "press" the button with the keyboard. – Joshua Goldberg Jan 25 '19 at 15:18
2

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

jzd
  • 23,473
  • 9
  • 54
  • 76
  • I thought I might have to. I think using Alt+Y as dogbane suggested will suffice for now. – Andez Jan 25 '11 at 12:43
  • @Andez, yes dogbane's solution should work fine, but if you need to just use y or n, then you will have to customize the dialog. – jzd Jan 25 '11 at 13:04
0

Look at Stopping Automatic Dialog Closing

Rod Lima
  • 1,509
  • 26
  • 30