我正在嘗試爲使用JFrame和canvas的遊戲構建簡單的GUI。 Window
是擴展JFrame類的類,我用fillRect
方法填充黑色矩形。每次運行我的程序時,框架窗口都不是黑色,而是默認顏色。我不知道我的代碼有什麼問題。BufferStrategy無法正常工作
package test1;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
/**
*
* @author sabertooth
*/
public class Test1 extends Canvas implements Runnable{
/**
* @param args the command line arguments
*/
private final static int width=600;
private final static int height=500;
private Window gui;
private Thread t;
private boolean status=false;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public static void main(String[] args) {
// TODO code application logic here
Dimension d=new Dimension(width,height);
Test1 mc=new Test1();
mc.gui=new Window();
mc.setPreferredSize(d);
mc.gui.setTitle("Welcome to my game");
mc.gui.add(mc);
mc.gui.setLocationRelativeTo(null);
mc.gui.setVisible(true);
Test1 t1=new Test1();
t1.start();
}
@Override
public void run() {
while(status)
{
update();
render();
}
}
public void render(){
}
public void update(){
BufferStrategy bs=getBufferStrategy();
if(bs==null)
{
createBufferStrategy(3);
return;
}
Graphics g=bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public synchronized void start(){
setStatus(true);
t=new Thread(this, "Game Thread");
t.start();
}
}
DoubleDouble的答案可能是正確的,但爲什麼JFrame我想知道?如果你只想通過BufferStrategy在畫布上繪製,我想你會想完全繞過Swing及其內部機制(如雙緩衝)。否則,你不妨在你的JFrame中使用JPanel,並讓Swing爲你做低級別的東西。我建議你使用普通的AWT窗口。 – Gimby