更新文本字段时无效的线程访问异常

时间:2015-03-12 22:39:07

标签: java multithreading swt thread-exceptions

我尝试使用可运行的线程更新属于另一个类的文本字段,但我发现线程访问无效'异常。

我的代码是:

 Thread t2 = new Thread () {

    public void run () {
        System.out.println("t2 thread içindeyim.");
        try {
            String sql =  " RESTORE DATABASE Genius3"+
                          " FROM DISK = '"+collected.getdbpath()+"'"+
                          " WITH MOVE 'GeniusIII_Data' TO 'C:\\SQLDATA\\Genius3.mdf',"+
                          " MOVE 'GeniusIII_Log' TO 'C:\\SQLDATA\\Genius3_1.ldf'";

            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url);
            stmt = con.prepareStatement(sql);
            rs = stmt.executeQuery();}
            catch (Exception ef) {ef.printStackTrace();}
            finally {

           ekran5.text_1.setText("done");

           }        
    }
};

和其中包含该文本字段的其他类;

 public class ekran5 {

public static Label islemlabel;

public static Composite composite_1 ;
public static Label detail;
 public static  Text text_1;
public static void start(){


composite_1 = new Composite(Loader.composite, SWT.BORDER | SWT.EMBEDDED);
composite_1.setBackground(SWTResourceManager.getColor(192,192,192));
composite_1.setBounds(362, 83, 668, 536);

islemlabel = new Label(composite_1, SWT.NONE);
islemlabel.setFont(SWTResourceManager.getFont("Arial CYR", 10, SWT.NORMAL));
islemlabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
islemlabel.setBounds(10, 448, 84, 15);
islemlabel.setText("\u0130\u015Flem Detay\u0131");

text_1 = new Text(composite_1, SWT.BORDER);
text_1.setBounds(10, 469, 628, 37);
}

}

在finally块中,我更新了文本字段,但由于这个原因,它给了我一个无效的线程访问异常。

1 个答案:

答案 0 :(得分:1)

在SWT中,只允许UI线程更新小部件尝试使用Display.syncExec执行所有UI更新。 (或者,可以使用UI作业。)

同时阅读SWT常见问题解答将是明智之举,这听起来像是一个常见问题解答。