JOptionPane - 将keylistener添加到showOptionDialog

edi*_*thk 1 java swing joptionpane

我正在开发Java Swing应用程序.

当我退出应用程序时,会弹出optionDialog,它会询问我是否要在退出之前保存文件.

我想要做的是optionDialog上有三个按钮(YES,NO,CANCEL)我想让optionDialog通过箭头键而不是tab键来改变按钮的焦点.如何在optionDialog中为按钮创建关键监听器?

到目前为止,这是我的代码

Object[] options = {" YES "," NO ","CANCEL"};

int n = JOptionPane.showOptionDialog(Swing4.this,
        "File haven't save yet." +
        " \n Are you want to save the file?",                                   
        "Confirm Dialog",
        JOptionPane.YES_NO_CANCEL_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        null,     //do not use a custom Icon
        options,  //the titles of buttons
        options[1]); //default button title                 

if(n == JOptionPane.YES_OPTION){            
    if(helper.updateFile("text.txt", gatherAllContent(), Swing4.this)){
        System.exit(0);
    }
    label.setText("There is something wrong on quit");

}else if(n == JOptionPane.NO_OPTION){
    System.exit(0);
}else if(n == JOptionPane.CANCEL_OPTION){
    System.out.println("Cancel");
}
Run Code Online (Sandbox Code Playgroud)

Nán*_*ser 6

不可能这样做showOptionDialog,而是你需要JOptionPane为自己创造一个.您正在寻找的是Container.getFocusTraversalKeys().这是一个使用右键更改按钮焦点的工作片段(Tab仍然有效):

    JOptionPane optionPane = new JOptionPane("File haven't save yet." +
            " \n Are you want to save the file?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
    JDialog dialog = optionPane.createDialog("Confirm Dialog");
    Set<AWTKeyStroke> focusTraversalKeys = new HashSet<AWTKeyStroke>(dialog.getFocusTraversalKeys(0));
    focusTraversalKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.VK_UNDEFINED));
    dialog.setFocusTraversalKeys(0, focusTraversalKeys);
    dialog.setVisible(true);
    dialog.dispose();
    int option = (Integer) optionPane.getValue();
Run Code Online (Sandbox Code Playgroud)