简体   繁体   中英

Set text on jlabel on main form from Thread

I have a java application in which I call threads for executing some stuff:

public class ThreadTest implements Runnable {
private final int functionNumber;
public static mainForm main = new mainForm();
private final int time2start;
public static YourClass obj  = new YourClass();
public ThreadTest(int functionNumber, int time2start, YourClass obj){
this.functionNumber = functionNumber;
this.time2start = time2start;

}
 @Override
public void run(){

try{Thread.sleep(time2start);}catch(Exception ex){}//Time Delay before executing methods
switch(functionNumber){
    case 1:
        obj.runFirst();
        break;
    case 2:
        obj.runSecond();
        main.appendText("Something");
        break;
    case 3:

{
    try {
        obj.runThird();
    } catch (IOException ex) {
        Logger.getLogger(ThreadTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}
        break;

And this is method in my main form with swing gui on which i want to append text from thread:

 void appendText(String text){
  generalStatus.setText(text);
 }

How is this achieved? I am guessing i need to use repaint or something?

Update the GUI component (JLabel) from another thread except Swing thread can not be done directly. But you can use a synchronized thread with Swing thread using SwingUtilities.invokeLater. GUI components can be updated inside a thread like this,

void appendText(String text) {
    final String Text=text;
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            generalStatus.setText(Text);
        }
    });
}

Whenever you want to update your GUI components in any other thread except Swing thread you should use this mechanism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM