BufferStrategy 不起作用 [英] BufferStrategy not working
问题描述
我正在尝试使用 JFrame 和画布为游戏构建简单的 gui.Window
是一个扩展 JFrame 类的类,我使用 fillRect
方法来填充黑色矩形.每次我运行我的程序时,框架窗口都不是黑色,而是默认颜色.我不知道我的代码有什么问题.
I am trying to do build simple gui for a game using JFrame and canvas. Window
is a class which extends JFrame class and I am using fillRect
method to fill rectangle of black color. Every time I run my program the frame window is not black it is of default color. I don't know what is wrong with my code.
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();
}
}
推荐答案
你的问题在这里:
Test1 t1=new Test1();
t1.start();
您已经设置了一个名为 mc 的 Test1 并将其添加到您的窗口中.然后创建一个新的 Test1 并告诉新的 Test1 开始更新,即使它没有被添加到任何东西中.
You already have set up a Test1 named mc and added it to your Window. Then you create a new Test1 and tell the new one to start updating, even though it isn't added to anything.
改为启动 mc...
mc.start();
您也可以在此处添加这一行,让窗口在启动时自行展开:
You can also add this line here to have the window expand itself when it starts:
mc.gui.pack();
mc.gui.setVisible(true);//Set it above this line in main()
当我执行上述操作并使用 JFrame 而不是您使用 Window 的地方时,代码会起作用.
The code works when I do the above and use a JFrame instead of where you use Window.
这篇关于BufferStrategy 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!