Failed to execute runnable (org.eclipse.swt.SWTException: Widget is disposed)原因以及解决办法

以下错误是本人学习中碰到的,以后碰到继续完善:

SWT编程中,当一个类中有一个线程 的时候,这个shell打开又关闭,这样重复几次的时候就会出现这样一个问题:

Failed to execute runnable (org.eclipse.swt.SWTException: Widget is disposed);

解决办法:经过查资料,以及调试,这个问题是这个shell关闭的时候,其中的某些标签或者什么的也被销毁了,而此时还在往里面写东西;就会出现这样的错误;下面是代码的修改:

应该会很明白;

<span style="color: rgb(70, 70, 70);">未修改前
thread=new Thread(new Runnable() {
                     public void run() {
                             while (!shell.isDisposed()) {
                                     display.asyncExec(new Runnable() {
                                             public void run() {
                                                    </span><span style="color:#ff0000;">        label_5.setText(AddUsers.time);</span><span style="color:#464646;">
                                             }
                                     });
                                     try {
                                             Thread.sleep(1000);
                                     } catch (InterruptedException e) {
                                             e.printStackTrace();
                                     }
                             }
                     }
             });
             thread.start();
             shell.addDisposeListener(new DisposeListener() {
                     @SuppressWarnings("deprecation")
                     public void widgetDisposed(DisposeEvent arg0) {
                             thread.stop();
                     }
           });</span>
修改后
<span style="color:#464646;">thread=new Thread(new Runnable() {
			public void run() {
				while (!shell.isDisposed()) {
					display.asyncExec(new Runnable() {
						public void run() {
							</span><span style="color:#ff6600;">if(!label_5.isDisposed()){
								label_5.setText(AddUsers.time);
							}</span><span style="color:#464646;">
						
						}
					});
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		thread.start();
		
		shell.addDisposeListener(new DisposeListener() {
			@SuppressWarnings("deprecation")
			public void widgetDisposed(DisposeEvent arg0) {
				thread.stop();
			}
		});</span>
总结:SWT中,当一个线程在一个类中的时候,这个类的实例被销毁了,其中的某些标签要被使用的时候,一定要注意这个标签是否被销毁,很简单的做法就是加判断。

总结2:不同线程之间的共享资源要放在共享区使用


发布了43 篇原创文章 · 获赞 18 · 访问量 7万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章