栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从另一个线程更新SWT对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从另一个线程更新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 OFFOCUS
上面的代码中的,那么我将始终得到
NullPointerException
…但是3秒钟的延迟使我的GUI线程有足够的时间处于就绪状态,因此无法通过
NullPointerException
.....

在这种情况下,您必须有效地使用

wait
and
yield
方法…否则将导致“很难找到错误” …即等待UI正确实例化然后屈服…

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

port
并且您的GUI线程
asynchronously
正在该端口上侦听。

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414477.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号