I am developing Java Swing application.
When I quit the application, optionDialog will pop out and it will ask me if I want to save the file before quit.
What I want to do is there are three button on optionDialog ( YES, NO, CANCEL) I want to make the optionDialog change the focus of the button by arrow key instead of tab key. How to create key listener for button in optionDialog?
So far, here is my code
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");
}
It's not possbile to do this with showOptionDialog
, instead you need to create a JOptionPane
for yourself. What you are looking for is Container.getFocusTraversalKeys(). Here is a working snippet to change button focus with the right key (Tab still works):
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();