how to set the default selected option as NO_OPTION in a JoptionPane
843805Nov 22 2006 — edited Nov 22 2006This is just an example program to create the same scenario in the project.When clicked on OK button, it will pop up a JOptionPane confirm dialog with YES-NO buttons.I want to set the default selected button as NO button. In the below program, the keyboard focus is set on NO button, but in the look and feel the selection is still YES button. Can anyone suggest a solution to make both the focus on NO button?
public class Test extends JPanel implements ActionListener{
Test() {
JButton btn = new JButton("OK");
this.add(btn);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object[] o = {"Yes", "No"};
JOptionPane p = new JOptionPane("Are u sure?",JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_OPTION,null,o,null);
//p.setWantsInput(false);
p.setInitialSelectionValue(o[1]);
try {
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//p.setFocusCycleRoot(false);
p.setInitialValue(o[1]);
//p.getRootPane().getDefaultButton().requestFocusInWindow();
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.FALSE);
p.createDialog(this, "").setVisible(true);
if(p.getValue() == o[0]) {
System.out.println("yes");
}else if(p.getValue() == o[1]) {
System.out.println("no");
}
//p.setWantsInput(true);
//p.showConfirmDialog(this, "Are u sure?");
//p.setInitialSelectionValue(new Integer(JOptionPane.NO_OPTION));
}
public static void main(String[] args) {
Test t = new Test();
JFrame f = new JFrame();
f.getContentPane().add(t);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
f.setVisible(true);
}