转载至:https://blog.csdn.net/sangjinchao/article/details/53052897
双缓冲实现方法:https://blog.csdn.net/sangjinchao/article/details/53052897
java用JFrame类会出现闪烁问题
原JFrame代码:
package cn.game;
/*
* GameUtil类
*/
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class GameUtil {
private GameUtil() {
}
public static Image getImage(String path) {
BufferedImage bi = null;
try {
URL u = GameUtil.class.getClassLoader().getResource(path);
bi = ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
return bi;
}
}
package cn.game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* 飞机游戏主窗口
*/
public class MyGameFrame extends JFrame {
Image back = GameUtil.getImage("images/background2.jpg"); //创建images包把要用图片放进去,再把位置写上
Image plane = GameUtil.getImage("images/plane.png");
int planeX = 270, planeY = 900;
public void paint(Graphics g) {
super.paint(g);
g.drawImage(back, 0, 0, 658, 1000, null, null);
g.drawImage(plane, planeX, planeY, 100, 100, null, null);
planeY--;
}
class paintThread extends Thread {
@Override
public void run() {
super.run();
while (true) {
repaint();
try {
Thread.sleep(20); // 单位Ms
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 初始化窗口
public void launchFrame() {
this.setTitle("PlaneGame");
this.setVisible(true);
this.setSize(658, 1000);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new paintThread().start();
}
public static void main(String[] args) {
MyGameFrame f = new MyGameFrame();
f.launchFrame();
}
}
运行程序,出现闪烁现象,GameUtil类内容不变 ,把MyGameFrame类的代码改下,改用JPanel类可解决此问题
修改后代码:
package cn.game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* 飞机游戏主窗口
*/
public class MyGameFrame extends JPanel {
Image back = GameUtil.getImage("images/background2.jpg"); //创建images包把要用图片放进去,再把位置写上
Image plane = GameUtil.getImage("images/plane.png");
int planeX = 270, planeY = 900;
public void paint(Graphics g) {
super.paint(g);
g.drawImage(back, 0, 0, 658, 1000, null, null);
g.drawImage(plane, planeX, planeY, 100, 100, null, null);
planeY--;
}
class paintThread extends Thread {
@Override
public void run() {
super.run();
while (true) {
repaint();
try {
Thread.sleep(20); // 单位Ms
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 初始化窗口
public void launchFrame() {
JFrame jf = new JFrame();
jf.add(this);
jf.setTitle("PlaneGame");
jf.setVisible(true);
jf.setSize(658, 1000);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new paintThread().start();
}
public static void main(String[] args) {
MyGameFrame f = new MyGameFrame();
f.launchFrame();
}
}
修改完后再运行代码发现以无闪烁问题