我有一些線程的簡單應用程序,我需要從某個線程更新SWING GUI(我使用Netbeans)。從線程更新Swing GUI
這就是我需要更新我的主要形式有:
public class mainForm extends javax.swing.JFrame {
private gameControll obj;
public mainForm() {
initComponents();
}
public void runAuto(){
ThreadTest th1 = new ThreadTest(1, 1, obj);
ThreadTest th8 = new ThreadTest(8, 95000, obj);
ThreadTest th2 = new ThreadTest(2, 100000, obj);
ThreadTest th3 = new ThreadTest(3, 120000, obj);
ThreadTest th4 = new ThreadTest(4, 140000, obj);
ThreadTest th22 = new ThreadTest(22, 1000, obj);
Thread thread1 = new Thread(th1);
Thread thread2 = new Thread(th2);
Thread thread3 = new Thread(th3);
Thread thread4 = new Thread(th4);
Thread thread22 = new Thread(th22);
Thread thread8 = new Thread(th8);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread22.start();
thread8.start();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mainForm app = new mainForm();
app.setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField pathtbox;
}
現在我有一些線程:
public class ThreadTest implements Runnable {
public static mainForm main = new mainForm();
private final int functionNumber;
private final int time2start;
public ThreadTest(int functionNumber, int time2start, gameControll 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:
//System.out.println("case 1");
obj.runFirst();
break;
case 2:
// System.out.println("case 2");
obj.runSecond();
break;
case 3:
{
try {
obj.runThird();
} catch (IOException ex) {
Logger.getLogger(ThreadTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
break;
...
,並在其他一些I類有:
public void runFirst(){
System.out.println("I need to show this text on jlabel5");
}
代碼的每個部分都在不同的文件(類)中。 我將如何在這裏實現Swing工作,以便能夠在我的主GUI形式上顯示文本?
你可能想看看http://docs.oracle.com/javase/7/docs/api/javax /swing/SwingUtilities.html#invokeLater(java.lang.Runnable),它在GUI線程上執行操作。 – Henrik 2014-10-27 13:37:53
因爲我是Java初學者,所以我無法真正找到答案,我嘗試過但沒有成功。初學者的文檔不可讀。根據我的例子,一段簡單的代碼將會很棒,如果有人可以編寫它的話。如果沒有,我會繼續谷歌。 – BlankName 2014-10-27 13:41:24
@BlankName,Henrik鏈接了特定方法的文檔。你讀過它嗎?您可以通過將訪問Swing組件的代碼封裝到java.lang.Runnable實現中並將其實例傳遞給SwingUtilities.invokeLater(Runnable)來更新您的GUI。 – predi 2014-10-27 13:53:16