我在学习写java游戏时,遇到屏幕一只不断闪烁,更改刷新时间也没有办法,使用双缓冲来解决这个问题,我该怎样实现,试着重写update方法但结果还是不行,我这里自己重写了paint方法
public class Cuckoo extends JFrame {
//管理所有组件
public void init(){ //初始化组件
/*注册组件*/
mainWindow();
}
//绘制游戏窗口
public void mainWindow(){
/*设置窗口位置(相对于屏幕),宽高*/
setBounds(700,250,288,512); //x,y屏幕位置,width,height窗口大小
setTitle("Flapp Birds"); //在窗口添加游戏名字
/*java窗口在默认情况下隐藏的*/
setVisible(true); //设置窗口可见(默认是false)
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //关闭窗口和程序
setResizable(false); //禁用窗口可调尺寸
while(true){ //让窗口自动刷新
repaint();;
try{
Thread.sleep(300); //线程休眠50ms,控制刷新频率
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
/*画笔*/
public void paint(Graphics graphics){
super.paint(graphics); //重新绘制图片
drawBackGround(graphics); //加入背景图片
moveGround(graphics); //加入移动墙
Bird(graphics); //加入小鸟
}
/*绘制游戏背景*/
int moveLeft = 0; //背景向后移动
public void drawBackGround(Graphics graphics){
Image bg = new ImageIcon("res/bg_main.png").getImage();//加载本地图片
graphics.drawImage(bg,moveLeft,0,null); //设置背景参数(xy为在窗口位置)
moveLeft -= 2; //每次向左移动减2dp
}
/*移动墙*/
public void moveGround(Graphics graphics){
Image bgWall = new ImageIcon("res/bg_wall.png").getImage();//加载本地图片
graphics.drawImage(bgWall,0,410,null); //设置背景参数(xy为在窗口位置)
}
/*让小鸟动起来*/
int i = 1; //调用bird的3张图片动画
public void Bird(Graphics graphics){
Image bgBird = new ImageIcon("res/bulebird"+ i +".png").getImage();//加载本地图片
graphics.drawImage(bgBird,115,260,null); //设置背景参数(xy为在窗口位置)
i++;
if(i > 3){
i = 1;
}
}
//程序启动
public static void main(String[] args) {
new Cuckoo().init(); //启动程序
}
}