我的「問題」可以通過以下描述。假設我們有一個密集的過程,我們希望在後臺運行並更新Swing JProgress欄。解決方案很簡單:如何委派的SwingWorker的發佈到其他方法
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
/**
* @author Savvas Dalkitsis
*/
public class Test {
public static void main(String[] args) {
final JProgressBar progressBar = new JProgressBar(0,99);
SwingWorker<Void, Integer> w = new SwingWorker<Void, Integer>(){
@Override
protected void process(List<Integer> chunks) {
progressBar.setValue(chunks.get(chunks.size()-1));
}
@Override
protected Void doInBackground() throws Exception {
for (int i=0;i<100;i++) {
publish(i);
Thread.sleep(300);
}
return null;
}
};
w.execute();
JOptionPane.showOptionDialog(null,
new Object[] { "Process", progressBar }, "Process",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, null, null);
}
}
現在假設我有很多方法需要很長時間。例如,我們有一種從服務器下載文件的方法。或另一個上傳到服務器。或者任何真的。將發佈方法委派給這些方法的正確方法是什麼,以便他們可以適當地更新GUI?
是我迄今發現的是這個(假設法「amethod方法」存在於其他一些包爲例):
import java.awt.event.ActionEvent;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
/**
* @author Savvas Dalkitsis
*/
public class Test {
public static void main(String[] args) {
final JProgressBar progressBar = new JProgressBar(0,99);
SwingWorker<Void, Integer> w = new SwingWorker<Void, Integer>(){
@Override
protected void process(List<Integer> chunks) {
progressBar.setValue(chunks.get(chunks.size()-1));
}
@SuppressWarnings("serial")
@Override
protected Void doInBackground() throws Exception {
aMethod(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
publish((Integer)getValue("progress"));
}
});
return null;
}
};
w.execute();
JOptionPane.showOptionDialog(null,
new Object[] { "Process", progressBar }, "Process",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, null, null);
}
public static void aMethod (Action action) {
for (int i=0;i<100;i++) {
action.putValue("progress", i);
action.actionPerformed(null);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
它的工作原理,但我知道這沒啥事。有什麼想法嗎?
如果我們只有一種可怕的長方法會怎樣?我不是downvoting,但這不是一個解決方案 – Xorty 2010-05-25 21:33:12
如果我的答案不好,你可以downvoting。但我讀到了這樣一個問題:「例如我們有一種方法可以從服務器上下載文件,或者另一種方法上傳到服務器,或者任何其他方式」......所以我想有很多方法,而不僅僅是一個可怕的方法長 ? – Istao 2010-05-26 04:46:32
我遇到的問題是可以從代碼的不同部分調用這些方法。而他們需要刷新的gui元素並不總是相同的。通過我的解決方案,我可以創建一個通用方法,並且每次創建一個新的擺動工人時,我都可以在我的GUI上確定工藝方法。 – 2010-05-26 19:35:25