java - SwingUtilites : how to return values from another thread in Java?

标签 java multithreading swing input swingutilities

我正在尝试用 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/

相关文章:

java - 如何在一个面板中加载图像和菜单?

java - 使用按钮数组调试 JFrame

java - Spock stub 在功能方法中不起作用

java - 如何以编程方式根据文件名设置 Drawable

android - 如何在 onPause() 中保存对象?

java - 让程序等待直到单击按钮

java - 从另一个线程调用 timer.cancel() 后,TimerTask 不会立即停止?

java - Restful : how to dynamically extend an API path's (or available resources)?

java - org.postgresql.Driver 在 NetBeans 中不工作

java - GWT、Vaadin、SmartGwt、ExtGwt ?---来自 Swing