1. 程式人生 > >用滑鼠畫圓(java GUI)

用滑鼠畫圓(java GUI)

話不多說,先看效果

當然你也可以發揮腦洞繪製更更棒的

原始碼如下:

package javaBasic;

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

public class DrawPoint {
	public static void main(String[] args) {
		new MyFrame("drawPoint");
	}
}

class MyFrame extends JFrame{
	ArrayList points = null;
	
	MyFrame(String s){
		super(s);
		points= new ArrayList();
		setLayout(null);
		setBounds(350,350,400,300);
		this.addMouseListener(new Monitor());
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public void paint(Graphics g) {
		Iterator i = points.iterator();
		while(i.hasNext()) {
			Point p = (Point)i.next();
			g.setColor(Color.pink);
			g.fillOval(p.x,p.y,10,10);
		}
	}
	
	public void addPoint(Point p) {
		points.add(p);
	}
}

class Monitor extends MouseAdapter{
	public void mousePressed(MouseEvent e) {
		MyFrame mf = (MyFrame)e.getSource();
		mf.addPoint(new Point(e.getX(),e.getY()));
		mf.repaint();
	}
}