Reputation: 4585
If I have a method that needs to return something, and it needs to display something on the UI to do that (for example to ask the user a question), I use java.awt.EventQueue.invokeLater(new Runnable() {...});
to run it on the UI thread (Android does something similar using runOnUiThread()
). How do I return something from that Runnable
? For example:
public String askQuestion()
{
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
String response = JOptionPane.showInputDialog(null, "What is 2+2?");
//how do I return this response object to the method?
}
});
}
I can't use a final local variable because the compile won't allow me to assign to it. I can use a class variable and access it using Class.this.<variable>
but is that the best/only way to accomplish this?
Edit: I need to return things other than String
too, this was just an example.
Upvotes: 2
Views: 2308
Reputation: 13066
You can proceed as follows:
public String askQuestion()throws Exception
{
final StringBuilder sBuilder = new StringBuilder();
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
String response = JOptionPane.showInputDialog(null, "What is 2+2?");
sBuilder.append(response);
}
});
return sBuilder.toString();
}
This could also be solved in following way:
String sResponse;//make sResponse a field of class xyz
public String askQuestion()throws Exception
{
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
String response = JOptionPane.showInputDialog(null, "What is 2+2?");
sResponse = response;
}
});
return sResopnse;
}
Upvotes: 3