Search code examples
javastringswingcomparisonjoptionpane

JOptionPane action on cancel button


The code I'm trying to compile:

import javax.swing.JOptionPane;

public class Comienzo
{

    public static void main()
    {
        String nombrepersonaje = JOptionPane.showInputDialog("Introduce el nombre de tu personaje");

        if (JOptionPane.OK_CANCEL_OPTION == JOptionPane.CANCEL_OPTION)
            Principal.main(new String[] {});
        else
            //do other stuff

        if (nombrepersonaje.equals(""))
            Comienzo.main();
        else
            JOptionPane.showMessageDialog(null, "¡Bienvenido... " + nombrepersonaje + "!");
    }
}

This class and method is called from another class (thing I learnt in this website), now I'd like to ask why Eclipse is telling me I'm comparing identical expressions, what I'm trying to do is: if I press cancel button, go back to Principal#main class, I've tried too with

if (JOptionPane.OK_CANCEL_OPTION == JOptionPane.CANCEL_OPTION)
{
    Comienzo.main();
}

But what I'm getting even if I type things in the InputDialog is looping the program, seems that after else whatever I'm writing is "dead code" which I don't understand why.

I'm trying even to remove the brackets after else and put

else if {nombrepersonaje.equals("")) 
    Comienzo.main();
else 
    JOptionPane.showMessageDialog(null, "¡Bienvenido... " + nombrepersonaje + "!");

Any ideas?


Solution

  • You have to compare the returned value of the method showInputDialog, which in this case is a String, with null (the showInputDialog returns null, if you click the Cancel button):

    public class Class
    {
        public static void main(String[] args)
        {
            String result = JOptionPane.showInputDialog(null, "Are you serious?");
    
            if(result == null)
                System.out.println("YOU ARE DEFINETELY SERIOUS!");
        }
    }