gpt4 book ai didi

java - SWT - asyncExec 将输出定向到列表小部件

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:14 25 4
gpt4 key购买 nike

我正在尝试使用 Display.asyncExec() 方法在生成 SWT 列表小部件时将状态更新打印到它们,而不是在程序完成时将更新转储到列表中。我不断收到 java.lang.NullPointerException。我不明白我做错了什么。该程序工作正常,直到我尝试使用单独的线程并使用 Display.asyncExec 方法。任何建议表示赞赏。

错误:“异常:从线程“Thread-0”中的 UncaughtExceptionHandler 抛出 java.lang.NullPointerException”

我的 CustomOutputStream 类:

import java.io.IOException;
import java.io.OutputStream;
import org.eclipse.swt.widgets.List;

/**
This class extends from OutputStream to redirect output to a SWT List widget
**/
public class CustomOutputStream extends OutputStream {

private List list;
private StringBuilder sb;
private Runnable runnable;

public CustomOutputStream(List list) {
this.list = list;
sb = new StringBuilder();
}

@Override
public void write(int b) {
// redirects data to the text area upon newline character
if(String.valueOf((char)b).equals("\n") ){
list.getDisplay().asyncExec(new Runnable() {
public void run() {
if(!list.isDisposed() ) {
// redirects data to the text area
list.add(sb.toString());
// scrolls the text area to the end of data
list.select(list.getItemCount() - 1);
list.showSelection();
list.deselectAll();
}
}
});
runnable.run();
sb.setLength(0);
}
else{
sb.append(String.valueOf((char)b));
}
}

}

在我的 DVS 类(class)中:

public class DVS implements Runnable{
private PrintStream log;
// constructor
public DVS( CustomOutputStream LOG) {
log = new PrintStream(LOG);
run();
}
public void run() {
System.setOut(log);
System.setErr(log);
/**
code that invokes System.out.println() ....
**/
}
}

在我的主课中:

Public List list = new List(shell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
Public CustomOutputStream log = new CustomOutputStream(list);
DVS algo = new DVS(log);
Thread thread = new Thread(algo);
thread.start();

最佳答案

我没有看到任何初始化 runnable 的地方,因此当您尝试调用 runnable.run() 时,它将为 null

public class CustomOutputStream extends OutputStream {

// ...
private Runnable runnable;

public CustomOutputStream(List list) {
this.list = list;
sb = new StringBuilder();
}

@Override
public void write(int b) {
if(String.valueOf((char)b).equals("\n") ){
// ...
runnable.run();
// ...
}
// ...
}

}

关于java - SWT - asyncExec 将输出定向到列表小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32875717/

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