我正在开发 Java Swing 应用程序。
当我退出应用程序时,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");
}
最佳答案
用 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();
关于java - JOptionPane - 添加 keylistener 到 showOptionDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15876427/