1
我在互聯網上發現了一個用於創建2D圖形遊戲的培訓,並且基於該代碼編寫了下面的代碼,但是當我編譯這個時候什麼也沒有發生! 它只是顯示一個沒有任何內容的窗口。通過使用drawString和drawLine我真的希望看到一些東西,但窗口是空的!有什麼問題 ? 是代碼錯誤?還是我使用錯誤的方法?在java圖形中使用緩衝區
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends Canvas {
BufferStrategy strategy;
boolean gameRunning = true;
public Game() {
JFrame jf = new JFrame("My Graphic thingy !");
JPanel panel = (JPanel) jf.getContentPane();
panel.setPreferredSize(new Dimension(800, 600));
panel.setLayout(null);
setBounds(0, 0, 800, 600);
panel.add(this);
setIgnoreRepaint(true);
jf.pack();
jf.setResizable(false);
jf.setVisible(true);
jf.createBufferStrategy(2);
strategy = jf.getBufferStrategy();
}
public void gameLoop() {
long lastLoopTime = System.currentTimeMillis();
while (gameRunning) {
lastLoopTime = System.currentTimeMillis();
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, 800, 600);
g.drawString("HellO", 12,12);
g.drawLine(10, 10, 30, 30);
g.dispose();
strategy.show();
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
Game g = new Game();
g.gameLoop();
}
}