韩顺平 java 第33讲 绘图技术
2015-10-10 14:58
393 查看
绘图原理
Component类提供了两个和绘图有关的最重要的方法:1. paint(Graphics g)绘制组件的外观
2. repaint()刷新组件的外观
3. 当组件第一次在屏幕显示的时候,程序会自动的调用paint()方法来绘制组件
4. 在以下三种情况下,paint()将会被调用:窗口的大小发生变化,窗口最小化和最大化,repaint函数被调用
package com.chen; import java.awt.*; import javax.swing.*; public class Draw extends JFrame{ MyPanel mp; public static void main(String[] args) { Draw d = new Draw(); } public Draw(){ mp = new MyPanel(); this.add(mp); this.setSize(400,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } //自己定义的面板,是用于绘图和显示绘图的区域 class MyPanel extends JPanel{ //覆盖JPanel的paint方法 //Graphics 是绘图的重要类,可以理解成是一只画笔 public void paint(Graphics g){ //1.调用父类函数完成初始化任务 super.paint(g); g.drawOval(100,50,60, 60);//先画一个圆 g.setColor(Color.green);//改变画笔颜色 g.drawLine(10, 30, 100, 250);//直线 g.drawRect(20, 20, 40, 50);//矩形 g.setColor(Color.blue); g.fillRect(50, 90, 20, 25);//填充矩形 Image im = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/zuijin.png")); g.drawImage(im, 100, 100, 40, 40, this); g.setFont(new Font("黑体",Font.BOLD,30)); g.drawString("Hello,陈", 100, 200); } }
画坦克
package com.chen; import java.awt.*; import javax.swing.*; public class Draw extends JFrame{ MyPanel mp; public static void main(String[] args) { Draw d = new Draw(); } public Draw(){ mp = new MyPanel(); this.add(mp); this.setSize(800,600); this.setLocation(200, 100); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } class MyPanel extends JPanel{ Hero hero; public MyPanel(){ hero = new Hero(10, 10); } public void paint(Graphics g){ super.paint(g); g.fillRect(0, 0, 600, 600); //画坦克 this.drawTank(hero.getX(), hero.getY(), g, 0, 0); } public void drawTank(int x,int y,Graphics g,int direct,int type){ //判断是什么类型的坦克 switch(type){ case 0: g.setColor(Color.cyan); break; case 1: g.setColor(Color.yellow); break; } //判断方向 switch(direct){ case 0: g.fill3DRect(x, y, 5, 30,false); g.fill3DRect(x + 15, y, 5, 30,false); g.fill3DRect(x + 5, y + 5, 10, 20,false); g.fillOval(x + 5, y + 10, 10, 10); g.drawLine(x + 10, y, x + 10, y + 15); } } } class Tank{ int x = 0,y = 0;//坦克的坐标 public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public Tank(int x,int y){ this.x = x; this.y = y; } } class Hero extends Tank{ public Hero(int x, int y) { super(x, y); } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树