从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();
}
}
我可能走错了方向。也许我应该用JPanel
和ActionListener
一起使用?还是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 楼答案
你的第一个“粗略示例”离有效解决方案不远(如果我正确理解了这个问题):
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)
好…;-)