簡體   English   中英

在Thread的主窗體上的jlabel上設置文本

[英]Set text on jlabel on main form from Thread

我有一個Java應用程序,在其中調用線程來執行一些操作:

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;

這是我的主要形式中帶有swing gui的方法,我想在該方法上附加線程中的文本:

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

如何實現的? 我猜我需要使用重塗顏料或其他東西嗎?

從Swing線程以外的其他線程更新GUI組件(JLabel)不能直接完成。 但是您可以使用SwingUtilities.invokeLater將同步線程與Swing線程一起使用。 可以在這樣的線程內更新GUI組件,

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

每當您要在除Swing線程之外的任何其他線程中更新GUI組件時,都應使用此機制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM