Reputation: 8135
public void aMethod(){
new Thread(new Runnable() {
public void run() {
int decide = JOptionPane.showConfirmDialog(null, confirmName?, JOptionPane.YES_NO_OPTION);
}
}).start();
System.out.println("Number of decison " + decide); //Can't find symbol "decide"
}
Upvotes: 0
Views: 534
Reputation: 28598
I don't think it's possible to do this with an anonymous class as the runnable class. You need to create a named class, that has a getter for the value of the 'decide' variable.
The problem is of course, that the main thread must wait until the created thread is finished before calling the getter to get the value of the 'decide' variable.
Given this, it seems dubious why you would be using a separate thread in the first place to show the dialog.
If you still want to do this, the main thread needs to call Thread.join on the created thread before calling the getter to get the value of 'decide'.
Upvotes: 1
Reputation: 70731
You can define custom fields in your Runnable
subclass and pass them through the constructor:
public class MyRunnable implements Runnable {
private int decide;
public MyRunnable(int decide) {
this.decide = decide;
}
public void run() {
...
}
}
As for why you need to invoke Swing methods on their own thread, you can read this article: Threads and Swing. In fact, you shouldn't be creating your own thread but instead just schedule it on the Swing event dispatch thread:
SwingUtilities.invokeLater(new MyRunnable(decide));
Upvotes: 1