0
我試圖找出如何從一個JOptionPane
變量設置爲正在運行的主線程。基於該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;
}
}
}
}
什麼是你真正想達到什麼目的?您發佈的代碼(假設AsyncPopup作品所暗示的)10秒後顯示彈出,那麼每一秒開始。你的問題中的措辭意味着做相反的事情(顯示彈出窗口然後更新主線程對象的狀態)。 – SimonC 2012-03-06 06:49:59
檢查了這一點http://docs.oracle.com/javase/7/docs/api/java/awt/SecondaryLoop.html – MahdeTo 2012-03-06 12:28:44
有一個主循環是一個簡單的計數器。我正在嘗試從用戶處獲得輸入而不停止主循環。對話框的響應會影響主循環。在這個例子中,10秒後出現一個彈出對話框而不暫停主循環(x == 10)。它僅在x == 10時出現。我需要對話框的響應來確定是否需要重置計數器。不過,我需要計數器在等待響應時繼續。我將查看可能解決我的問題的SecondaryLoop鏈接。 – 2012-03-06 13:31:08