我正在开发Java Swing应用程序。
退出应用程序时,会弹出optionDialog,并询问我是否要在退出之前保存文件。
我要做的是在optionDialog上有三个按钮(是,否,取消)。我想让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();