2013-04-14 36 views
2

我想運行新的Swing線程並將參數傳遞給它們。 事情是這樣的:Swing Runnable參數

String str; 

SwingUtilities.invokeLater(new Runnable() { 
public void run() { 
    Play game = new Play(this.str); 
     game.setVisible(true); 
    } 
}); 

我發現answer, how to pass a parameter into thread,但我不知道如何重建它爲我的需要。 感謝您的想法。

+0

你可以使用的SwingWorker或創建一個實現Runnable接口,帶你想通過它的參數的自定義類 – MadProgrammer

+0

這是我的第一個圖形java應用程序,它非常簡單。 @trashgod理念的作品,所以我不會重建我的代碼,但我會在下次你的通知:) – Andrew

回答

3

或者,您的匿名Runnable可以在封閉範圍內訪問最後領域:

final String str = "one"; 

SwingUtilities.invokeLater(new Runnable() { 
    @Override 
    public void run() { 
     Play game = new Play(str); 
     game.setVisible(true); 
    } 
}); 
+0

謝謝,它的工作;) – Andrew

+0

不客氣。有關參考,另請參閱[*定義和啓動線程*](http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html)。 – trashgod

0

你不能。改爲新建一個Thead

編輯:這是一些代碼,因爲你很困惑。

import javax.swing.SwingUtilities; 

public class Main { 
    public static void main(String[] args) { 
    SwingUtilities.invokeLater(new MyThread("StackOverflow")); 
    } 

    private static class MyThread extends Thread { 
    String text; 

    public MyThread(String text) { 
     this.text = text; 
    } 

    @Override 
    public void run() { 
     System.out.println(this.text); 
    } 
    } 
} 
+0

我很抱歉,但我沒有嘗試你的代碼,但感謝您的幫助;) – Andrew

+0

更多[常見](http: //docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html),'MyRunnable實現了Runnable'。 – trashgod