How do I create a showOptionDialog method that defaults to "no"?

3

I want confirmation messages from my system to behave with the default value of "no". I did this by doing this:

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]);

I just want to create a method to reuse this snippet of code and I'm not getting it. Do I have to override the showOptionDialog method of java?

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

How would you do that?

    
asked by anonymous 14.10.2017 / 03:37

1 answer

2

You can do this:

    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);

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

    
14.10.2017 / 04:00