GUI ------ paint

import java.awt.*;

public class Testpint {
	public static void main(String[] args) {
//		new TFPaint().lunchPaint();
		new TFPaint();
	}
}

class TFPaint extends Frame{
	
	/*
	public void lunchPaint() {
		this.setBounds(200, 200, 640, 640);
		this.setBackground(Color.BLUE);
		this.setVisible(true);
	}
	*/
	
	
	TFPaint(){
		this.setBounds(200, 200, 200, 200);
		this.setBackground(Color.BLUE);
		this.setVisible(true);
	}	
	
	
	public void paint(Graphics g) {
		Color c = g.getColor();
		g.setColor(Color.BLACK);
		g.fillRect(60, 60, 30, 30);
		g.setColor(Color.CYAN);
		g.fillOval(80, 80, 40, 40);
		g.setColor(c);
	}
}

paint方法是container类的一个方法,其能够实现绘图的功能,其是本身自带的方法,我们相当于重写了这个方法,在调用时我们用到了参数(Graphics g),一个画笔,用g来实现绘画,Frames是container的一个子类,所以我们在Frame里重写了Paint方法。

注;Color c = g.getColor(),和g.setColor(c),相当于把画笔用完后,重新置为原来的颜色。

Paint 的一个实例,外加MouseMonitor的介绍。

import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class TestPaint2 {
	public static void main(String[] args) {
		new TFpaint("Draw");
	}
}

class TFpaint extends Frame{
	ArrayList pointList = null;
	
	TFpaint(String s){
		super(s);
		pointList = new ArrayList();
		this.setLayout(null);
		this.setBounds(200, 200, 400, 400);
		this.setBackground(Color.blue);
		this.setVisible(true);
		this.addMouseListener(new MyMouseMonitor());
	}
	
	public void paint(Graphics g ) {
		Iterator i = pointList.iterator();
		while(i.hasNext()) {
			Point p = (Point)i.next();
			g.setColor(Color.BLACK);
			g.fillOval(p.x, p.y, 10, 10);
		}	
	}
	
	public void addPoint(Point p) {
		pointList.add(p);
	}
}

class MyMouseMonitor extends MouseAdapter{
	public void mousePressed(MouseEvent e) {
		TFpaint f = (TFpaint) e.getSource();
		f.addPoint(new Point(e.getX(),e.getY()));
		f.repaint();
	}
	
}

基本要求:实现在一个界面上鼠标每点击一下,就会生成一个点,

基本思路:要有一个Frame,用来显示界面,由于需要在这个界面上产生点,所以我们有鼠标点击产生点,即有对鼠标的监听,而我们要在监听后产生点,所以我们有Paint方法用来绘图,而他绘制的图就是产生一个点。

其中较为麻烦的就是,必须在指定位置(即鼠标点击的位置产生一个点)如何来找到这个位置,在此时我们在MouseMonitor中利用e.getSource获得信息,其中e是点击这个事件发生时,我们把他包装成一个类,传输给Monitor(其内部含有事件处理方法)

注:在Frame中我们要显示多个点,所以我们建立了一个ArrayList,用来存储点类型数据,在Frame中存储的过程就相当于画在了上面,

getSource是重新定义到一个新的来源,如上文,我们把e的getSource赋值给了f(一个Frame)相当于对frame进行添加,即Frame拿到了属于Monitor的画笔,我们通过e.getx,e和e.gety,进行定位,x,y,确定的就是鼠标点击的点,addpoint,相当于点一下在Frame上添加一个点,而print就是把哪些点用圆圈表示出来,

由于点数据是用ArrayList存储的所以对应的我们进行索引的时候用了Iterator,只要在列表里有一个点就用圆圈表示出来。

repaint,是将画面重新显示出来,感觉相当于刷新界面,如果没有,在界面上虽然有点但是他不显示,只有重传界面(即界面刷新时才会出现)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值