有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从JOptionPane到线程的java异步通信

我试图弄清楚如何将变量从JOptionPane设置为正在运行的主线程。根据JOptionPane对话框的结果,这将影响该主线程中的某些逻辑。下面是一个粗略的例子:

public class MainThread {       
    public static void main(String[] args) {            
        Timer timer = new Timer();    
        timer.scheduleAtFixedRate(new MyTask(), 0, 1000);           
    }    
}

public class MyTask extends TimerTask {    
    int x = 0;
    AsyncPopUp popUp = new AsyncPopUp();

    public void run() {         
        // code to detect reset here
        // x = 0;    
        x++;
        System.out.println(x);          
        if (x==10){
            new AsyncPopUp().showMessage();
        }    
    }    
}

public class AsyncPopUp {    
    void showMessage() {    
        Thread t = new Thread(new Runnable() {    
            @Override
            public void run() {    
                int response = JOptionPane.showConfirmDialog(null, "Reset Counter?",
                               "Question", JOptionPane.YES_NO_OPTION);

                if (response == 0){                     
                    System.out.println("Send Message to task to reset");
                }                                   
            }    
        });         
        t.start();    
    }    
}

我可能走错了方向。也许我应该用JPanelActionListener一起使用?还是SwingWorker

谢谢

我认为这可能有效——如果这是一种不好的做法,请告诉我:

public class Async {
    private Boolean response = false;
    private Thread t;

    public void start() {
        new Timer().schedule(new TimerTask() {    
            int x = 0;

            @Override
            public void run() {    
                System.out.println(x);

                if (x == 10) {
                    t = new Thread(new DoTask());
                    t.start();
                }

                if (response == true) {
                    System.out.println("true");
                    x = 0;
                    response = false;

                } else {
                    System.out.println("false");
                }    
                x++;    
            }

        }, 0, 1000);    
    }

    public class DoTask implements Runnable {    
        @Override
        public void run() {    
            int optionResponse = JOptionPane.showConfirmDialog(null,
                    "Reset Counter?","Question", JOptionPane.YES_NO_OPTION);

            if (optionResponse == 0) {
                response = true;
            }    
        }    
    }    
}

共 (1) 个答案

  1. # 1 楼答案

    你的第一个“粗略示例”离有效解决方案不远(如果我正确理解了这个问题):

    • MyTask类中添加一个reset()方法,如果用户决定重置,该方法将执行任何应该发生的操作
    • AsyncPopUp类中添加一个构造函数,该类需要MyTask对象作为参数,并将其保存到task字段中
    • MyTask类中执行new AsyncPopUp时,将this作为构造函数参数传递
    • 你在哪里System.out.println("Send Message to task to reset")呼叫task.reset()

    顺便说一句:注意if (response == JOptionPane.YES_OPTION)看起来比if (response == 0)好…;-)