我正在尝试使用Display.asyncExec()方法在状态更新生成时将状态更新打印到SWT List小部件,而不是在程序完成时将更新转储到List。我不断收到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课中:

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的地方,因此当您尝试调用null时它将是runnable.run()

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();
            // ...
        }
        // ...
    }

}

09-15 18:19