javamultithreadingswtthread-exceptions

Invalid thread access exception while updating textfield


I'm trying to update a textfield which belongs to another class using a runnable thread, but I'm getting 'invalid thread access' exception.

My code is:

 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");

           }        
    }
};

and the other class which has that textfield in it ;

 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);
}

}

In the finally block, I'm updating the textfield but it gives me an invalid thread access exception because of this.


Solution

  • In SWT only the UI thread is allowed to update widgets try using Display.syncExec to perform all the UI updates. (Alternatively, a UI job can be used.)

    Also reading the SWT FAQ would be a wise move, this sounds like a FAQ to me.