SWT - asyncExec将输出定向到List小部件

时间:2015-09-30 21:11:46

标签: java list swt java-threads

我正在尝试使用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();

1 个答案:

答案 0 :(得分:0)

我没有看到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();
            // ...
        }
        // ...
    }

}