JOptionPane won't Work: Aim use the Default option (customize the answer buttons)

43 views Asked by At

This is the Text, it won't work I allready checked it with the You AI

import javax.swing.JOptionPane; 

public class Test_showConfirmDialog1 {
public static void main(String[] args) {
    Object[] options = {"Yes", "No"};
        int Tester = JOptionPane.showConfirmDialog(null, "Do you smoke?", "",                    
JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE, null, options, options[0]);
    JOptionPane.showMessageDialog(null, "Tester = " + Tester);
    }

Eclipse says: show.ConfirmDialog doesn't work. why? (I am a Beginner, I don't know most of Java but the code simply corrected woould be allready helpfull, I am sure I will figure out the rest by myself.)

1

There are 1 answers

0
Berc07 On BEST ANSWER

It's because you use showConfirmDialog, instead of using showOptionDialog.

Here is the code that is using the showOptionDialog:


import javax.swing.*;

public class Main {
    
    public static void main(String[] args) {
        Object[] options = {"Yes", "No"};
        int tester = JOptionPane.showOptionDialog(null, "Do you smoke?", "",
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                null, options, options[0]);
        // The variable 'tester' contains the index of the selected button
        JOptionPane.showMessageDialog(null, "Tester = " + tester);
        // If you want to view directly the selected option (Yes or No):
        JOptionPane.showMessageDialog(null, "Selected: " + options[tester]);
    }
    
}

If you only want to use Yes or No options, Java swing has a built-in dialog for that (it uses showConfirmDialog):

import javax.swing.*;

public class Main {
    
    public static void main(String[] args) {
        int tester = JOptionPane.showConfirmDialog(null, "Do you smoke?", "",
                JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
        // Yes = 0; No = 1; (clicking the close icon) = -1
        JOptionPane.showMessageDialog(null, "Tester = " + tester);
    }
    
}

I hope it helped.