我认为您收到java.lang.NullPointerException 是因为您试图在创建 GUI 组件之前访问它。理想情况下,您应该等待创建 gui 组件...例如...
我在一个单独的线程中创建一个单一的 GUI...像这样
package test;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class GUIThread implements Runnable
{
private Display display;
private Label label;
public Display getDisplay(){
return display;
}
public void run()
{
display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
shell.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,false));
label = new Label(shell,SWT.NONE);
label.setText(" -- ");
shell.open();
shell.pack();
while (!shell.isDisposed()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose();
}
public synchronized void update(final int value)
{
if (display == null || display.isDisposed())
return;
display.asyncExec(new Runnable() {
public void run() {
label.setText(""+value);
}
});
}
}
在我的主要方法中,我做了这样的事情......
package test;
import org.eclipse.swt.widgets.Display;
public class Main
{
public static void main(String[] args) throws Exception
{
final GUIThread gui = new GUIThread();
Thread t = new Thread(gui);
t.start();
Thread.sleep(3000); // POINT OF FOCUS
Display d = gui.getDisplay();
for(int i = 0; i<100; i++)
{
System.out.println(i + " " + d);
gui.update(i);
Thread.sleep(500);
}
}
}
现在如果我们在上面的代码中注释掉POINT OF FOCUS,那么我总是会得到NullPointerException...但是3秒的延迟让我的GUI线程有足够的时间进入就绪状态,因此它不会通过NullPointerException.....
在这种情况下,您必须有效地使用 wait 和 yield 方法...否则会导致“很难找到错误”...即等待 UI 正确实例化然后屈服... .
另外,实际处理是在主线程中完成的,GUI 是在单独的线程中运行的……为了正确通信,最好有一些共享和同步的数据结构……或者可以使用套接字通信来完成……您的主线程填充了一些 port 和您的 GUI 线程 asynchronously 在该端口上侦听......
希望这可以解决您的问题....