我使用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 +線程遊戲循環(輸入+更新+繪製)。我錯了嗎?
這應該拋出一個NullPointerException,因爲你永遠不會初始化't1'...你需要一個't1 = new Thread(this);'wherewhere。請注意,無論您試圖達到什麼目標,幾乎肯定會有更好的方法。 – assylias
螺紋和擺動部件不能混用。閱讀http://docs.oracle.com/javase/tutorial/uiswing/concurrency/ – Qwerky