Initial focus on JOptionPane OK button

2

I have the following JOptionPane :

AsyoucanseethefocusisontheCancelTeacher

IneedthisfocustocomeoutOK,butIhavenoideahowtodothis.Mycode:

JPanelpanel=newJPanel();JLabellabel=newJLabel("Digite a senha para iniciar o auxilio:");
    JPasswordField pass = new JPasswordField(10);
    panel.add(label);
    panel.add(pass);
    String[] options = new String[]{"OK", "Cancelar maestro"};
    int option = JOptionPane.showOptionDialog(null, panel, "Inicio de auxilio",
            JOptionPane.PLAIN_MESSAGE, JOptionPane.NO_OPTION,
            null, options, options[1]);
    if (option == 0) {
        ...
     }...

Could someone guide me?

    
asked by anonymous 14.07.2016 / 19:17

1 answer

4

I tested here and just changed the index of% with% that the OK button was selected:

int option = JOptionPane.showOptionDialog(null, panel, "Inicio de auxilio",
            JOptionPane.PLAIN_MESSAGE, JOptionPane.NO_OPTION,
            null, options, options[0]);

According to documentation , this is the method you used, see the parameters that it receives:

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

where the two last options are:

  

options - an array of objects indicating the possible choices the user can make; if the objects are components, they are rendered properly; non-String objects are rendered using their toString methods; if this parameter is null, the options are determined by the Look and Feel

     

initialValue - the object that represents the default selection for the dialog; only meaningful if options is used; can be null

The last parameter represents the value initially selected when opening the dialog box and if you pass options , there will be no options (in your case buttons) selected. You were passing the second value reference ( null ), so the second button was focused. Vectors always start from index 0 and go to the index "sizeVector - 1" .

    
14.07.2016 / 19:28