2013-07-30 22 views
1

我使用setContentPane(new Gamepanel())從另一個類調用此類。 爲什麼線程t1沒有調用run方法?Jpanel調用線程

public class GamePanel extends JPanel implements Runnable { 

    public static int WIDTH = 1024; 
    public static int HEIGHT = WIDTH/16 * 9; 
    private Thread t1; 
    boolean running; 


    public void addNotify(){ 
     Dimension size = new Dimension(WIDTH,HEIGHT); 
     setPreferredSize(size); 
     running = true; 
     t1.start(); 
    } 


    public void paintComponent (Graphics g){ 
     g.setColor(Color.WHITE); 
     g.fillRect(0, 0, WIDTH, HEIGHT); 
     g.setColor(Color.BLACK); 
     g.fillOval(200, 200, 50, 50); 
    } 


    public void run() { 
     while (running){ 
      System.out.println("Runs"); 
    } 
} 

編輯

好吧,其實初始化線程的伎倆。像那

public class GamePanel extends JPanel implements Runnable { 

    public static int WIDTH = 1024; 
    public static int HEIGHT = WIDTH/16 * 9; 
    private Thread t1; 
    boolean running; 


    public void addNotify(){ 
     Dimension size = new Dimension(WIDTH,HEIGHT); 
     setPreferredSize(size); 
     running = true; 
     t1 = new Thread(this); 
     t1.start(); 
    } 



    public void paintComponent (Graphics g){ 
      g.setColor(Color.WHITE); 
     g.fillRect(0, 0, WIDTH, HEIGHT); 
     g.setColor(Color.BLACK); 
     g.fillOval(200, 200, 50, 50); 
    } 


    public void run() { 
     while (running){ 
     System.out.println("Runs"); 
     } 

    } 

} 

我假設這是一個正確的方式開始在啓動方法中放置一個遊戲循環。 我打算去JFrame + JPanel +線程遊戲循環(輸入+更新+繪製)。我錯了嗎?

+0

這應該拋出一個NullPointerException,因爲你永遠不會初始化't1'...你需要一個't1 = new Thread(this);'wherewhere。請注意,無論您試圖達到什麼目標,幾乎肯定會有更好的方法。 – assylias

+2

螺紋和擺動部件不能混用。閱讀http://docs.oracle.com/javase/tutorial/uiswing/concurrency/ – Qwerky

回答

0

你的問題不清楚。 Thread1應該做什麼? 請給我們詳細說明你打電話給T1的方式,以及你如何建立你的班級。 順便說一句,你把T1放在私人存取處,而且在你的班級中沒有看到任何getter/setter。 如果你想操縱它,你必須定義一些方法。

如果你不給一個繼承了一個Thread對象的對象,它肯定它不起作用。 請參閱:http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html 線程類實現自己的Runnable接口。

我的結論與你的代碼是不可能告訴你什麼是錯的,他們有太多的問題領域。

安東尼。

0

您未初始化線程,它必須拋出一個NullPointerException。 試一下 在main方法

t1=new Thread(new GamePanel()); 
t1.start(); 

//沒有通知或根據您的REQ修改。 不明確的問題