Danny
Danny

Reputation: 179

JOptionPane trying to retrieve which button is selected

I'm currently trying to get this part of my code to compare which button the user chooses to the button it self. At the moment it automatically displays the else which is Test2.

Object usersChoice;

    Object[] options = { "Go on a journey!", "Exit, i'm tired." };
    usersChoice = JOptionPane.showOptionDialog(null, "Hello Melissa :)", "Sunshine program",
    JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
    null, options, options[0]);

    if(usersChoice == options )
    {
        JOptionPane.showMessageDialog(null, "Test1");
    } else {
        JOptionPane.showMessageDialog(null, "Test2");
    }

Upvotes: 0

Views: 32

Answers (1)

Thunderforge
Thunderforge

Reputation: 20575

The problem is with this code (I've moved the declaration of usersChoice for clarity):

Object[] options = [...]
Object usersChoice = JOptionPane.showOptionDialog([...])

The method JOptionPane.showOptionDialog() returns an int. Since that's a primitive, it gets autoboxed to an Integer.

Now you have this code:

if(usersChoice == options )

You are comparing an Object[] to an Object (more specifically, an Integer). That will always be false because they are different types.

Also remember that in Java, using == checks for equality on primitives, but Objects compared this way will be compared by their memory locations. Use .equals() instead to compare Objects.

Upvotes: 3

Related Questions