[英]Java Swing GUI updating/changing from method - freezing in loop
基本上,我有這段代碼,它最初與控制台 i/o 一起工作,現在我必須將它連接到UI 。 這可能是完全錯誤的,我嘗試了多種方法,盡管最終還是凍結了 GUI。
我試圖將控制台 I/O 重定向到 GUI 滾動窗格,但 GUI 仍然凍結。 可能它必須對線程做一些事情,但我對它的了解有限,所以我需要更深入的解釋如何在當前情況下實現它。
這是 GUI 類上的按鈕,包含需要更改此 GUI 的方法。
public class GUI {
...
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.startTest(index, idUser);
}
});
}
這是來自另一個包含 Question 類實例的類的 startTest 方法。
public int startTest() {
for (int i = 0; i < this.numberofQuestions; i++) {
Question qt = this.q[i];
qt.askQuestion(); <--- This needs to change Label in GUI
if(!qt.userAnswer()) <--- This needs to get string from TextField
decreaseScore(1);
}
return actScore();
}
問問題方法:
public void askQuestion() {
System.out.println(getQuestion());
/* I've tried to change staticaly declared frame in GUI from there */
}
用戶回答方法:
public boolean userAnswer() {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
if( Objects.equals(getAnswer(),userInput) ) {
System.out.println("Correct");
return true;
}
System.out.println("False");
return false;
}
感謝幫助。
您認為它與線程有關是正確的。
當您嘗試在 Swing 線程中執行需要很長時間處理(例如下載大文件)的代碼時,Swing 線程將暫停以完成執行並導致 GUI 凍結。 這是通過在單獨的線程中執行長時間運行的代碼來解決的。
正如Sergiy Medvynskyy在他的評論中指出的那樣,您需要在SwingWorker類中實現長時間運行的代碼。
實現它的一個好方法是:
public class TestWorker extends SwingWorker<Integer, String> {
@Override
protected Integer doInBackground() throws Exception {
//This is where you execute the long running
//code
controller.startTest(index, idUser);
publish("Finish");
}
@Override
protected void process(List<String> chunks) {
//Called when the task has finished executing.
//This is where you can update your GUI when
//the task is complete or when you want to
//notify the user of a change.
}
}
使用TestWorker.execute()
啟動工作器。
這個網站提供了一個關於如何使用 SwingWorker 類的很好的例子。
正如其他答案所指出的,在 GUI 線程上做繁重的工作會凍結 GUI。 您可以為此使用SwingWorker
,但在許多情況下,一個簡單的Thread
完成這項工作:
Thread t = new Thread(){
@Override
public void run(){
// do stuff
}
};
t.start();
或者,如果您使用 Java 8+:
Thread t = new Thread(() -> {
// do stuff
});
t.start();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.