Does anyone have experience with creating a JOptionPane
such as the YES_NO_OPTION
dialog and changing the default to "NO" while maintaining the keyboard shortcuts? I used an array of objects to populate the options of {"YES", "NO"}
and then in the JOptionPane.showOptionDialog
parameters I passed in those options. This works in changing the focus of the button, but removes the keyboard shortcuts for the buttons. Is there anyway to maintain the keyboard shortcuts while also changing focus? This is not a question of how to default to "NO" but rather how to maintain the keyboard shortcuts. The question "How to make JOptionPane.showConfirmDialog have No selected by default?" is asking about focus, no one ever answers how to maintain keyboard shortcuts. Here is a snippet of the code...
Object[] options = {"YES", "NO"};
int choice = JOptionPane.showOptionDialog(null, "Please choose yes/no", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
I don't think there's any "easy" way to do this. Instead, you're probably going to have to provide your own buttons.
So based on JOptionPane Passing Custom Buttons and Disable ok button on JOptionPane.dialog until user gives an input, you can provide your own JButton
s preconfigured the way you want them, for example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
JButton btnYes = new JButton("Yes");
btnYes.setMnemonic('s');
btnYes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(JOptionPane.YES_OPTION);
}
});
JButton btnNo = new JButton("No");
btnNo.setMnemonic('o');
btnNo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(JOptionPane.NO_OPTION);
}
});
JButton[] options = new JButton[] {btnYes, btnNo};
JOptionPane.showOptionDialog(
null,
"Help",
"More",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, btnYes);
}
protected static JOptionPane getOptionPane(JComponent parent) {
JOptionPane pane = null;
if (!(parent instanceof JOptionPane)) {
pane = getOptionPane((JComponent)parent.getParent());
} else {
pane = (JOptionPane) parent;
}
return pane;
}
}