基本上,我有这段代码最初与控制台 I/O 一起使用,现在我必须将其连接到UI。这可能是完全错误的,我已经尝试了多种方法,但最终仍然卡住了 GUI。
我尝试将控制台 I/O 重定向到 GUI 滚动 Pane ,但 GUI 仍然卡住。可能它必须对线程做一些事情,但我对它的了解有限,所以我需要更深入的解释如何在当前情况下实现它。
This is the button on GUI class containing the method that needs to change this GUI.
public class GUI {
...
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.startTest(index, idUser);
}
});
}
This is the method startTest from another class which contains instance of Question class.
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();
}
askQuestion method:
public void askQuestion() {
System.out.println(getQuestion());
/* I've tried to change staticaly declared frame in GUI from there */
}
userAnswer method:
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()
启动工作线程。
This网站提供了一个关于如何使用的很好的例子 SwingWorker 类。
关于Java Swing GUI 更新/更改方法 - 卡住在循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61459215/