public class PaintUtil3 extends JPanel{
/**
* 动态图片
*/
private static final long serialVersionUID = -5247450804494766145L;
private static BufferedImage image;
int y = 0;
int y1 = -600;
static {
image = loadImage("background.png");
}
/** 读取图片 */
public static BufferedImage loadImage(String fileName) {
try {
//同包下读取图片
BufferedImage img = ImageIO.read(PaintUtil3.class.getResource(fileName));
return img;
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
private void backgroundLogic() {
y += 5;
y1 += 5;
if(y >= 600) {
y = -600;
}
if(y1 >= 600) {
y1 = -600;
}
}
/** 启动程序的执行 */
public void action() {
Timer timer = new Timer(); //定时器对象
int interval = 10; //以毫秒为单位
timer.schedule(new TimerTask() {
public void run() { //定时干的那个事(每10毫秒走一次)
backgroundLogic();
repaint(); //重画(重新调用paint())
}
},interval,interval); //定时计划
}
/** 重写paint()画 g:画笔 */
public void paint(Graphics g) {
g.drawImage(image, 0, y, null);//在坐标(0,0)处画图,先画图再写字,不然会覆盖
g.drawImage(image, 0, y1, null);//在坐标(0,0)处画图,先画图再写字,不然会覆盖
g.setColor(Color.red);//设置颜色
g.drawString("abcde", 111, 111 );//打字
g.drawString("ABCDE", 300, 330);
}
public static void main(String[] args) {
JFrame frame = new JFrame("打飞机");
PaintUtil3 pu = new PaintUtil3();//要求PaintUtil3是继承 JPanel父类
frame.add(pu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 600);
frame.setLocationRelativeTo(null); //中间
frame.setVisible(true); //1)设计窗口可见 2)尽快调用paint()
pu.action();//执行才会动态
}
}
结果:背景向下移动