JavaAWT绘图实例

2016-05-22· 3946 次浏览
窗体: ``` import java.awt.Color; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class AWTDrawTest extends WindowAdapter{ //构造方法 public AWTDrawTest(){ Frame f = new Frame("绘图测试"); DrawCanvas dc = new DrawCanvas();//实例化画布 f.add(dc); f.addWindowListener(this);//添加关闭事件 f.setBackground(new Color(160,220,220));//设置背景颜色 f.setLocationByPlatform(true); f.setSize(600,400); f.setVisible(true); } @Override//重写方法 public void windowClosing(WindowEvent e){ System.exit(0); } //main方法 public static void main(String[] args){ new AWTDrawTest(); } } ``` 画布: ``` import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; class DrawCanvas extends Canvas{ //新建画布类 @Override//重写方法 public void paint(Graphics g){ Graphics2D g2 = (Graphics2D) g; g.setFont(new Font("楷体",Font.PLAIN,50));//设置字体 g.setColor(Color.RED);//设置颜色 g.drawString("AWT绘图演示",60,60);//画出字符串 g.drawLine(50,80,500,80);//画出一条直线 g.setColor(Color.BLUE);//设置颜色 g.drawRect(50,90,200,80);//画空心矩形 g.fillRect(300,90,200,80); g.fillArc(50,200,65,65,0,90);//画扇形 g.setFont(new Font("华文彩云",Font.PLAIN,64));//设置字体 g.setColor(new Color(8, 46, 84));//设置颜色 g.drawString("编程百科",90,300);//画出字符串 } } ``` 获取窗体边框的大小: ``` Insets set=frame.getInsets(); int top = set.top; //上边框厚度 int left = set.left; //左边框厚度 int right = set.right; //右边框厚度 int bottom = set.bottom; //底边框厚度 ``` 重写update,双缓冲技术解决重绘闪烁: ``` Image ImageBuffer = null;   Graphics GraImage = null;    public void update(Graphics g){     //覆盖update方法,截取默认的调用过程       ImageBuffer = createImage(this.getWidth(), this.getHeight());   //创建图形缓冲区       GraImage = ImageBuffer.getGraphics();       //获取图形缓冲区的图形上下文       paint(GraImage);        //用paint方法中编写的绘图过程对图形缓冲区绘图       GraImage.dispose();     //释放图形上下文资源       g.drawImage(ImageBuffer, 0, 0, this);   //将图形缓冲区绘制到屏幕上   } ```