您的位置:首页 > 编程语言 > Java开发

韩顺平 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 绘图 画坦克