awt学习笔记3
第三章 图 形
3.1-3.4
这一部分主要是说在使用Graphics这个内置对象应该注意的问题
1、fillRect()与drawRect()不同
drawRect(int x,int y, int x_add, int y_add)
第三个,第四个变量是增量
原文:
import java.applet.Applet;
import java.awt.*;
public class RectTest extends Applet{
public void paint(Graphics g){
g.drawRect(2,2,4,4);
}
}
画笔的变化 坐标(2,2)→(6,2)→(6,6)→(2,6)→(2,2)
而实际在操作的时候,是从点右下侧的像素画的,所以实际上绘制出来的矩形的宽度和高度是5个像素单位——而不是你所想象的4个像素单位
要想画成自己想要的长宽在调用的时候drawRect(int x,int y, int x_add-1, int y_add-1)就可以了
fillRect()是填充四个座标内的区域,所以不会有这样的问题
import java.applet.Applet;
import java.awt.*;
public class RectTest extends Applet{
public void paint(Graphics g){
g.fillRect(2,2,4,4);
}
}
填充(2,2)→(6,2)→(6,6)→(2,6)→(2,2)四个座标内的区域,所以是一个4个像素单位的矩形
2、Graphics引用是复制过来的
3、处理Graphics引用
原则:
如果只是覆盖传递Graphics引用的方法,像Component.paint()或Component.update(),那么然后你就可以什么也不管——处理引用则是调用者的责任。
如果是getGraphics方法中的一个得到一个对Graphics的引用,或者通过Graphics.create()创建一个Graphics,那么就有责任对它们进行处理
3.5绘制和填充形状
随机画直线,颜色随机,位置随机
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DrawRandomLine extends Applet {
@Override
public void paint(Graphics g) {
Dimension size = this.getSize();
int MAX_COLOR = 255;
int MAX_X = new Double(size.getWidth()).intValue();
int MAX_Y = new Double(size.getHeight()).intValue();
//随机产生三基色数值
int cr = new Double(Math.random()* MAX_COLOR).intValue();
int cg = new Double(Math.random()* MAX_COLOR).intValue();
int cb = new Double(Math.random()* MAX_COLOR).intValue();
//随机产生两个坐标点
int x1 = new Double(Math.random() * MAX_X).intValue();
int y1 = new Double(Math.random() * MAX_Y).intValue();
int x2 = new Double(Math.random() * MAX_X).intValue();
int y2 = new Double(Math.random() * MAX_Y).intValue();
//输出颜色及坐标信息
g.drawString("Color:r=" + cr + ",g=" + cg + ",b=" + cb, 0, 10);
g.drawString("Point A:x=" + x1 + ",y=" + y1, 0, 30);
g.drawString("Point B:x=" + x2 + ",y=" + y2, 0, 50);
Color c = new Color(cr, cg, cb);
g.setColor(c);
g.drawLine(x1, y1, x2, y2);
}
@Override
public void init() {
this.setSize(640, 480);
//设置按钮
Button b = new Button("repaint");
this.add(b);
b.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//注意:匿名内部类引用外部同名资源OuterClass.this.XXXX
//其实直接写repaint()就可以了,不过这样写可以知道谁调用的这个方法
DrawRandomLine.this.repaint();
}
}
);
}
}