[英]Java's Swing Threading
我的理解是,如果我啟動另一個線程來執行某些操作,我需要SwingUtilities.invokeAndWait
或SwingUtilities.invokeLater
來更新GUI,而我在所述線程中。 如果我錯了,請糾正我。
我想要完成的是相對簡單的:當用戶點擊提交時,我想(在執行任何操作之前)禁用提交按鈕,執行操作,並在操作結束時重新啟用按鈕。 我的執行操作的方法在返回結果時直接更新GUI(顯示結果)。
此操作基本上查詢服務器並返回一些結果。
到目前為止我所擁有的是:
boolean isRunning = false;
synchronized handleButtonClick() {
if ( isRunning == false ) {
button.setEnabled( false );
isRunning = true;
doAction();
}
}
doAction() {
new Thread() {
try {
performAction(); // Concern A
} catch ( ... ) {
displayStackTrace( ... ); // Concern B
} finally {
SwingUtilities.invokeLater ( /* simple Runnable to enable button */ );
isRunning = false;
}
}
}
對於我上面的兩個問題,我是否必須使用SwingUtilities.invokeAndWait
因為它們都會更新GUI? 所有GUI更新都圍繞更新JTextPane
。 我是否需要在我的線程中檢查我是否在EDT上,如果是,我可以調用我的代碼(無論是否更新GUI)而不使用SwingUtilities.invokeAndWait
?
編輯:這是我現在正在做的事情:
handleButtonClick() {
if ( isRunning == true )
return;
disable button;
SwingWorker task = new MyTask();
task.execute();
}
...inside MyTask
doInBackground() {
return performAction();
}
done() {
result = get();
enable button;
isRunning = false;
interpret result (do most of the GUI updates here);
}
雖然performAction()
執行了一些GUI更新,但我將它們包含在:
if ( SwingUtil.isEDT() )
doGUIupdate()
else
SwingUtil.invokeLater( new Runnable() {
run() {
doGUIupdate();
}
} );
希望這是朝着正確方向邁出的一步,如果您認為有更好的方法來處理我的情況,請發表評論。
在我看來,你幾乎不應該使用invokeAndWait()
。 如果某些事情需要一段時間才會鎖定你的UI。
使用SwingWorker
進行此類操作。 在Java SE 6中查看使用SwingWorker提高應用程序性能 。
您應該考慮使用SwingWorker
因為它不會阻止UI線程,而SwingUtilities
方法都將在EDT線程上執行,從而阻止UI。
我將簡單的Thread
保留在EventQueue.invokeLater(...)
,並且順利運行...
java.awt.EventQueue.invokeLater(new Runnable() {
public void run(){
new Thread(new Runnable(){
public void run(){
try{
EdgeProgress progress = EdgeProgress.getEdgeProgress();
System.out.println("now in traceProgressMonitor...");
while(true){
// here the swing update
if(monitor.getState() == ProgressMonitor.STATE_BUSY){
System.out.println(monitor.getPercentDone()/2);
progress.setProgress(monitor.getPercentDone()/2);
}else{
break;
}
Thread.sleep(5);
}
}catch(InterruptedException ie){}
}
}).start();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.