Reputation: 7
I'm trying to use a string created by JOptionPane in another JOptionPane. I tried making the string global. Am I doing this correctly?
import javax.swing.JOptionPane;
public class Dialogue
{
public static String reason = "";
public static void main(String[] args)
{
ask();
JOptionPane.showInputDialog("You're here because: " + reason);
}
public static void ask()
{
String reason = JOptionPane.showInputDialog("Why are you here?");
}
}
Upvotes: 0
Views: 475
Reputation: 4964
the string reason
is declarted as global and static variable, so ther is no need to redelrated is ask ()
method
public class Dialogue
{
public static String reason = "";
public static void main(String[] args)
{
ask();
JOptionPane.showInputDialog("You're here because: " + reason);
}
public static void ask()
{
reason = JOptionPane.showInputDialog("Why are you here?");
}
}
Upvotes: 1
Reputation: 7890
remove String
from ask
method (as by doing so you are creating a new local variable reason
)
keep it as
reason = JOptionPane.showInputDialog("Why are you here?");
Upvotes: 1
Reputation: 1926
In this statement:
String reason = JOptionPane.showInputDialog("Why are you here?");
You're creating a new String
. So the global variable and this one aren't referencing the same String
.
Do it like this:
reason = JOptionPane.showInputDialog("Why are you here?");
This way you're using the global variable, as you want.
EDIT:
I guess that you don't want an user input after asking why he's there, so I guess you would like to switch this:
JOptionPane.showInputDialog("You're here because: " + reason);
to this
JOptionPane.showMessageDialog(null, "You're here because: " + reason);
This way, it just gives an information, and doesn't wait for an user input.
Upvotes: 1