gpt4 book ai didi

java - SwingWorker 未正确运行 doInBackground

转载 作者:行者123 更新时间:2023-12-02 05:20:41 24 4
gpt4 key购买 nike

所以我进入了 SwingWorkers 来处理我使用不同的类和线程进行的文本操作。如下所示,我的 Swingworker 获取文件路径并扫描文本,将行传递给字符串。使用 getData(),我将扫描的字符串返回到我的主类。但是,直到我在 Worker 类的构造函数中运行方法 scanFile() 后,这才起作用。 所以我的问题是:为什么我的 SwingWorker 类无法正确运行 doInBackground()

public class ScanWorker extends SwingWorker<Void, Void> {

private File file;
private String text;

ScanWorker(File file) {
this.file = file;
}

@Override
protected Void doInBackground() throws Exception {
scanFile();
return null;
}

public String getData() {
return text;
}

private void scanFile() {
String line = "";
try {

Scanner scan = new Scanner(file);

while(scan.hasNextLine()) {
line = scan.nextLine();
if(!scan.hasNextLine()) {
text += line;
} else {
text += line + "\n";
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

最佳答案

  1. 您不应该添加自己的 getData()方法的返回值,因为这不是线程安全的。这正是 SwingWorker 试图通过提供自己的机制将结果传输回 Swing 线程来避免的情况。结果类型是 SwingWorker 的第一个类型参数,因此而不是 SwingWorker<Void,Void> ,你应该有SwingWorker<String,Void> .

  2. 更改 protected Void doInBackground()protected String doInBackground() (因为这是您的结果类型)。

  3. 删除 text字段,并返回来自 doInBackground() 的结果字符串.

  4. doInBackground() 返回结果后工作线程上的方法, done() 方法将在 Swing 线程上调用。你缺少那个方法。从该方法您可以调用 get() 检索结果。添加方法如下:

    @Override
    protected void done() {
    String result;
    try {
    result = get();
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    // Now do whatever you want with the loaded data:
    ...
    }
  5. SwingWorker 不会执行任何操作,直到您通过调用其 execute() 来启动它。方法。确保你正在这样做!

附注您不应该直接在字符串变量中构建文本,因为每次向其中追加一行时都会重新复制整个字符串,这会带来糟糕的性能。使用 StringBuilder 对于此类事情,请调用 toString()仅在最后才进行。

或者,由于如果您只想将文件再次连接在一起,则将文件拆分为行是没有意义的,因此您可以一次性读取完整文件:

@Override
protected String doInBackground() throws Exception {
return new String(
java.nio.file.Files.readAllBytes(file.toPath()),
java.nio.charset.StandardCharsets.UTF_8);
}

关于java - SwingWorker 未正确运行 doInBackground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26548043/

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