1/**//*
2 学习如何使用双缓冲消除闪烁,实现主要在 update()方法里
3*/
4import java.awt.*;
5import java.awt.event.*;
6import javax.swing.*;
7
8class TestCanvas extends Canvas
9{
10 private int x,y;
11
12 TestCanvas()
13 {
14 this.setSize(400, 400);
15 x=200;
16 y=50;
17 }
18
19 public void leftMove()
20 {
21 x-=50;
22 if(x<=-50) x=this.getWidth();
23 repaint();
24 }
25
26 public void rightMove()
27 {
28 x+=50;
29 if(x>=this.getWidth()) x=-50;
30 repaint();
31 }
32
33 public void upMove()
34 {
35 y-=50;
36 if(y<=-50) y=this.getHeight();
37 repaint();
38 }
39
40 public void downMove()
41 {
42 y+=50;
43 if(y>=this.getHeight()) y=-50;
44 repaint();
45 }
46
47 public void paint(Graphics g)
48 {
49 g.fillOval(x, y, 50, 50);
50 }
51
52 public void update(Graphics g) //实现消除闪烁
53 {
54 Image image; //创建一张和原来大小一样的图像
55 image=createImage(this.getWidth(),this.getHeight());
56 Graphics gp=image.getGraphics(); //获得此创建图像的 画笔
57 paint(gp); //调用paint 对此图像作画
58
59 g.drawImage(image, 0, 0, this); //将此图像画到(this)画布上
60 }
61
62}
63
64class MyKeyAdapter extends KeyAdapter
65{
66 TestCanvas tp;
67 MyKeyAdapter(TestCanvas tp)
68 {
69 this.tp=tp;
70 }
71 public void keyPressed(KeyEvent e)
72 {
73 if(e.getKeyCode()==KeyEvent.VK_LEFT)
74 tp.leftMove();
75 else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
76 tp.rightMove();
77 else if(e.getKeyCode()==KeyEvent.VK_UP)
78 tp.upMove();
79 else if(e.getKeyCode()==KeyEvent.VK_DOWN)
80 tp.downMove();
81 }
82}
83
84public class ClearUpFlicker extends JFrame
85{
86 ClearUpFlicker()
87 {
88 super("学习如何使用双缓冲消除闪烁");
89 setBounds(300, 150, 400, 400);
90 setVisible(true);
91 this.addWindowListener(new WindowAdapter()
92 {
93 public void windowClosing(WindowEvent e)
94 {
95 dispose();
96 System.exit(0);
97 }
98 });
99 }
100 public static void main(String[] args)
101 {
102 ClearUpFlicker jf=new ClearUpFlicker();
103 TestCanvas tp=new TestCanvas();
104 tp.addKeyListener(new MyKeyAdapter(tp));
105 jf.add(tp);
106 tp.requestFocusInWindow();
107 }
108
109}
110