gpt4 book ai didi

java - 如何在不卡住 GUI 的情况下调用 SwingWorker .get()?

转载 作者:搜寻专家 更新时间:2023-11-01 02:13:07 26 4
gpt4 key购买 nike

我做了一个样本来说明问题:

public class Worker extends SwingWorker<Integer, Integer> {
private GeneralUserInterface gui;

public Worker(GeneralUserInterface gui){
this.gui = gui;
}

@Override
protected Integer doInBackground() throws Exception {
int someResultToReturn = 10;

for(int i=0; i<100; i++){
Thread.sleep(50);//The Work
publish(i+1);//calls process, which updates GUI
}

return someResultToReturn;
}

@Override
protected void process(List<Integer> values) {
for (Integer val : values) {
gui.updateProgressBar(val);
}
}
}

private void jButtonDoWorkActionPerformed(java.awt.event.ActionEvent evt) {
Worker worker = new Worker(this);
worker.execute();

try {
int resultToGet = worker.get();//Obviously freezes the GUI
} catch (InterruptedException | ExecutionException ex) {}

//NEXT LINE NEEDS THE RESULT TO CONTINUE
}

public void updateProgressBar(int value){
this.jProgressBar1.setValue(value);
}

如您所料,对 worker.get() 的调用使 UI 无响应,这是正常的,因为它等待线程完成。这种问题一般是怎么解决的?

最佳答案

How is this kind of problem usually solved ?

通常您所做的是覆盖 Swingworker.done() 方法。当后台线程完成时,Done 在 GUI 线程中执行。然后你可以安全地调用 get 而不会阻塞并做任何你需要做的事情。

这是一种方法:

public class Worker extends SwingWorker<Integer, Integer> {
private GeneralUserInterface gui;

// omitted...

@Override
protected Integer doInBackground() throws Exception {
int someResultToReturn = 10;

for(int i=0; i<100; i++){
Thread.sleep(50);//The Work
publish(i+1);//calls process, which updates GUI
}

return someResultToReturn;
}

// omitted...

@Override
protected void done() {

try {
int resultToGet = worker.get();//Obviously freezes the GUI
} catch (InterruptedException | ExecutionException ex) {}

//NEXT LINE NEEDS THE RESULT TO CONTINUE
}
}

private void jButtonDoWorkActionPerformed(java.awt.event.ActionEvent evt) {
Worker worker = new Worker(this);
worker.execute();
}

但这可能不是最方便的设计。我发现最好将 GUI 的东西设为公共(public)类,然后将 swing worker 创建为非静态内部类。这样“完成”方法就可以轻松访问所有 GUI 私有(private)变量。

关于java - 如何在不卡住 GUI 的情况下调用 SwingWorker .get()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13424842/

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