Initial focus on the Joptionpane OK button

Asked

Viewed 448 times

2

I got the following JOptionPane:

inserir a descrição da imagem aqui

As you can see the focus is on the Cancel maestro option

I need this focus to be on OK, but I have no idea how to do that. My code:

    JPanel panel = new JPanel();
    JLabel label = new JLabel("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) {
        ...
     }...

Someone could guide me?

1 answer

4


I took the test here and just changed the index of options that the OK button is now selected:

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

According to the documentation, this is the method you used, see the parameters 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 it is passed null, there will be no option(in your case the buttons) selected. You were passing the second value reference(options[1]), so the second button was focused. Vectors always start from Indice 0 and go to Indice "sizeVetor - 1".

  • and if I want the focus to be in the password field?

  • @Viniciusleonardo change the initialValue for null that the focus goes to the text field.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.