2013-12-20 47 views
0

我一直在嘗試解決,但它永遠不會改變屏幕。我試圖使用在render()方法中看到的圖形。告訴我,如果渲染方法內部出現問題,我可以放鬆一下,因爲我似乎無法找到問題所在。爲什麼屏幕不會變色?

import java.awt.Canvas; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.image.*; 

import javax.swing.JFrame; 

public class Game extends Canvas implements Runnable { 
private static final long serialVersionUID = 1L; 
public static int width = 300; 
public static int height = width/16*9; 
public static int scale = 3; 

private Thread thread; 
private boolean running = false; 
private JFrame frame; 

public synchronized void start() { 
    thread = new Thread(); 
    thread.start(); 
    running = true; 
} 

public synchronized void stop() { 
    running = false; 
    try{ 
     thread.join(); 
    }catch(InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

public Game() { 
    Dimension size = new Dimension(width * scale, height * scale); 
    setPreferredSize(size); 

    frame = new JFrame(); 
} 

public void run() { 
    while(running) { 
     tick(); 
     render(); 
    } 
} 

void tick() {} 

public void render() { 
    BufferStrategy bs = getBufferStrategy(); 
    if(bs==null){ 
     createBufferStrategy(3); 
     return; 
    } 

    Graphics g = bs.getDrawGraphics(); 
    g.setColor(Color.BLACK); 
    g.fillRect(0, 0, getWidth(), getHeight()); 
    bs.dispose(); 
    bs.show(); 
} 
public static void main(String[] args) { 
    Game game = new Game(); 

    game.frame.setResizable(false); 
    game.frame.setTitle("Rain"); 
    game.frame.add(game); 
    game.frame.pack(); 
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    game.frame.setLocationRelativeTo(null); 
    game.frame.setVisible(true); 

    game.start(); 
} 

} 
+1

您在展示()之前將BufferStrategy放置()。那不好。 –

+0

我試過了。似乎沒有工作。 – user2469009

+0

您的代碼看起來與[此問題]非常相似(http://stackoverflow.com/questions/20547542/bufferstrategy-not-working/20547780#20547780)。我會嘗試比較你的代碼,因爲我認爲他們可能使用相同的教程。 – DoubleDouble

回答

1

讓我給你一個錯誤的堆棧跟蹤。

你的渲染方法甚至沒有在這裏被調用。
這是因爲你的run方法根本沒有被調用。
所有這一切背後的原因是,在線程創建時您沒有傳遞正確的Runnable對象。它創建一個空運行的線程。
在你的啓動方法,只需更換

thread = new Thread(); 

thread = new Thread(this); 

,它應該工作。

希望這有助於。請享用。

+0

它工作。感謝:D – user2469009

相關問題