Adol  
日历
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
统计
  • 随笔 - 2
  • 文章 - 6
  • 评论 - 5
  • 引用 - 0

导航

常用链接

留言簿(1)

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 
  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(400400);
 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, 5050);
 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, 00this);  //将此图像画到(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(300150400400);
 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
posted on 2009-08-12 23:18 Adol 阅读(221) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
 
Copyright © Adol Powered by: 博客园 模板提供:沪江博客