user6456810 user6456810 - 1 year ago 72
Java Question

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",
null, options, options[0]);

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download