gpt4 book ai didi

java - 从后台线程中的另一个类更新 GUI

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:01:12 26 4
gpt4 key购买 nike

我来自 .NET 环境,在该环境中,即使对于初学者来说,事件监听也很容易实现。但这次我必须用 Java 来完成。

我的伪代码:

主窗体-

public class MainForm extends JFrame {
...
CustomClass current = new CustomClass();
Thread t = new Thread(current);
t.start();
...
}

自定义类-

public class CustomClass implements Runnable {

@Override
public void run()
{
//...be able to fire an event that access MainForm
}
}

我找到了 this example但在这里我必须监听类似 this other one 中的事件.我应该把它们混在一起,我的 Java 技能水平太低了。你能帮我制定一个最佳解决方案吗?

最佳答案

我认为您正在寻找的是 SwingWorker .

public class BackgroundThread extends SwingWorker<Integer, String> {

@Override
protected Integer doInBackground() throws Exception {
// background calculation, will run on background thread

// publish an update
publish("30% calculated so far");

// return the result of background task
return 9;
}

@Override
protected void process(List<String> chunks) { // runs on Event Dispatch Thread
// if updates are published often, you may get a few of them at once
// you usually want to display only the latest one:
System.out.println(chunks.get(chunks.size() - 1));
}

@Override
protected void done() { // runs on Event Dispatch Thread
try {
// always call get() in done()
System.out.println("Answer is: " + get());
} catch (Exception e) {
throw new RuntimeException(e);
}
}

}

当然,在使用 Swing 时,您希望更新一些 GUI 组件而不是打印出来。所有 GUI 更新都应在事件调度线程上完成。

如果你只想做一些更新,而后台任务没有任何结果,你仍然应该在done()方法中调用get()。否则,doInBackground() 中抛出的任何异常都将被吞没 - 很难找出应用程序不工作的原因。

关于java - 从后台线程中的另一个类更新 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com