How do I create a showOptionDialog method that the default value is "no"?

Asked

Viewed 53 times

3

I want my system’s confirmation messages to behave with the default value "no". I have achieved this by doing so:

private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    Object[] options = {"Yes", "No"};
    JOptionPane.showOptionDialog(rootPane, "Deseja Excluir o Usuário?",
    "Titulo", 0, 3, null, options, options[1]);

screenshot

Only I want to create a method to reuse this chunk of code and I’m not getting it. I have to override the method showOptionDialog java?

I want to pass as parameter the message to be displayed and I want to return the option selected by the user.

How would you do that?

1 answer

2


You can do it:

    private static boolean perguntar(
            Component c,
            String mensagem,
            String titulo,
            boolean defaultOpt)
    {
        Object[] options = {"Sim", "Não"};
        int resposta = JOptionPane.showOptionDialog(
                c,
                mensagem,
                titulo,
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[defaultOpt ? 0 : 1]);
        return resposta == 0;
    }

To call this method:

boolean aceitou = perguntar(rootPane, "Deseja excluir o usuário?", "Título", false);

He will return true if the user clicks the "Yes" button and will return false if he clicks on the "No", close the window, press Esc or squeeze Enter immediately after the window opens.

Browser other questions tagged

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