坦克大战(一期)-解决闪烁问题(通过双缓冲解决)

Network
bingor_yhj 2 years ago
parent e119a9798c
commit 29c1d47f42

@ -12,8 +12,8 @@ public class Bullet extends Frame {
private int x, y; private int x, y;
private DirEnum dir; private DirEnum dir;
public static final int WIDTH = 8; public static final int WIDTH = 20;
public static final int HEIGHT = 8; public static final int HEIGHT = 20;
public static final int SPEED = 5; public static final int SPEED = 5;
public Bullet(int x, int y, DirEnum dir) { public Bullet(int x, int y, DirEnum dir) {

@ -22,7 +22,10 @@ public class Tank {
} }
public void paint(Graphics g) { public void paint(Graphics g) {
Color color = g.getColor();
g.setColor(Color.YELLOW);
g.fillRect(x, y, 50, 50); g.fillRect(x, y, 50, 50);
g.setColor(color);
moving(); moving();
} }

@ -5,6 +5,7 @@ import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter; import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.util.Objects;
/** /**
* @Author bingor * @Author bingor
@ -16,11 +17,13 @@ public class TankFrame extends Frame {
Tank tank = new Tank(200, 200, DirEnum.RIGHT); Tank tank = new Tank(200, 200, DirEnum.RIGHT);
Bullet bullet = new Bullet(200, 200, DirEnum.DOWN); Bullet bullet = new Bullet(200, 200, DirEnum.DOWN);
public static final int GAME_WIDTH = 800;
public static final int GAME_HEIGHT = 600;
public TankFrame() { public TankFrame() {
setTitle("Tank war"); setTitle("Tank war");
setSize(800, 600); setSize(GAME_WIDTH, GAME_HEIGHT);
setResizable(true); setResizable(true);
setVisible(true); setVisible(true);
@ -38,11 +41,28 @@ public class TankFrame extends Frame {
@Override @Override
public void paint(Graphics g) { public void paint(Graphics g) {
super.paint(g); // super.paint(g);
tank.paint(g); tank.paint(g);
bullet.paint(g); bullet.paint(g);
} }
//双缓冲,解决闪烁现象
Image offScreenImage = null;
@Override //在paint方法之前会被调用但是我做实验了闪烁现象似乎还是存在
public void update(Graphics g) {
// super.update(g);
if(Objects.isNull(offScreenImage)) {
offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT);
}
Graphics gOffScreen = offScreenImage.getGraphics();
Color color = gOffScreen.getColor();
gOffScreen.setColor(Color.WHITE);
gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
gOffScreen.setColor(color);
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}
//这里使用内部内的原因是只有TankFrame用到 //这里使用内部内的原因是只有TankFrame用到
class MyKeyListener extends KeyAdapter { class MyKeyListener extends KeyAdapter {

Loading…
Cancel
Save