0
this.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                int par1 = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit", "Exit?", JOptionPane.YES_NO_OPTION);
                if(par1==JOptionPane.YES_OPTION)
                {
                    System.exit(0);
                }
            }
        });

This is my code. How to I set the "No" button in JOptionPane requestFocus?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ken Wong
  • 109
  • 2
  • 2
  • 9

2 Answers2

2

Use JOptionPane.showOptionDialog and set the options and initialValue parameters.

public static int showOptionDialog(Component parentComponent,
                                   Object message,
                                   String title,
                                   int optionType,
                                   int messageType,
                                   Icon icon,
                                   Object[] options,
                                   Object initialValue)
                            throws HeadlessException

Try this:

Object[] options = { "YES", "NO" };
int par1 = JOptionPane.showOptionDialog(null, "Are you sure you want to exit", "Exit?",
    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
    null, options, options[1]);
if(par1==0)
{
     System.exit(0);
}

More JOptionPane

Iswanto San
  • 18,263
  • 13
  • 58
  • 79
0

Use this constructor:

JOptionPane(Object message, int messageType, int optionType,
        Icon icon, Object[] options, Object initialValue)

options represents all available buttons and initialValue is the button to be selected by default.

poitroae
  • 21,129
  • 10
  • 63
  • 81