我正在尝试用 Java 开发一个应用程序。 为了使 Swing 正常工作,我这样做了:
public static void main(String[] array){
String outerInput;
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
// I want this string input.
String input = JOptionPane.showInputDialog(
null,"Stop ?", JOptionPane.QUESTION_MESSAGE);
});
// How can I get this input value in String outerInput?
}
如何在我的主体中获取这个输入字符串?
最佳答案
您可以使用 AtomicReference<String>
以线程安全的方式在线程之间传递值。
正如 Hemal 所指出的,您需要在两个线程之间进行一些同步以确保它已被执行。例如,您可以使用 CountDownLatch 或使用 SwingUtilities.invokeAndWait(确保您不从 Swing 线程调用它!)
更新:这里是使用 AtomicReference 的完整示例和 CountDownLatch
public class Main {
public static void main(String[] args) throws InterruptedException {
final AtomicReference<String> result = new AtomicReference<String>();
final CountDownLatch latch = new CountDownLatch(1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String input = JOptionPane.showInputDialog(null, "Stop?", "Stop?", JOptionPane.QUESTION_MESSAGE);
result.set(input);
// Signal main thread that we're done and result is set.
// Note that this doesn't block. We never call blocking methods
// from Swing Thread!
latch.countDown();
}
});
// Here we need to wait until result is set. For demonstration purposes,
// we use latch in this code. Using SwingUtilities.invokeAndWait() would
// be slightly better in this case.
latch.await();
System.out.println(result.get());
}
}
另请阅读 this answer关于 GUI(和 Swing)应用程序的一般设计。
关于java - SwingUtilites : how to return values from another thread in Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418909/