您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从另一个线程更新SWT对象

从另一个线程更新SWT对象

我认为您正在获得,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.....

在这种情况下,您必须有效地使用waitand yield方法…否则将导致“很难找到错误” …即等待UI正确实例化然后屈服…

同样,实际的处理是在主线程中完成的,并且GUI在单独的线程中运行…要正确通信,最好具有一些共享和同步的数据结构…或者可以使用套接字通信来完成…主线程填充一些,port并且您的GUI线程asynchronously正在该端口上侦听。

希望这可以通过您的问题得到一些启示。

其他 2022/1/1 18:28:40 有546人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶