Search code examples
javastringswingcomparisonjoptionpane

Java (eclipse): Any way to System.out.println this String from a JOptionPane .showInputDialog?


Code's here:

import javax.swing.JOptionPane;


public class Comienzo {

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

        if (nombrepersonaje == null)
            Principal.main(new String[]{});
        else if (nombrepersonaje.equals(""))
            Comienzo.main();
        else 
            JOptionPane.showMessageDialog(null, "¡Bienvenido... " + nombrepersonaje + "!");

        Start.main();
    }    
}

I've tried since yesterday several ways to call a String, but it only works if String is defined before

    public static void main ()

So, question is this: How can I "System.out.println" String nombrepersonaje from another class in same Java Project?

Thanks in advance!


Solution

  • Create a field in the other class. Add a setter for the field. Create an instance of the class with new. Call the setter with the variable nombrepersonaje.

    public class Start {
         private String name;
         public void setName( String name ) { this.name = name; }
    
         public void run() {
              ...
         }
    }
    

    and in Comienzo:

    else {
        JOptionPane.showMessageDialog(null, "¡Bienvenido... " + nombrepersonaje + "!");
        Start start = new Start();
        start.setName(nombrepersonaje);
        start.run();
    }