生成内部三角形

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * 三角形
 * @author tiger
 * 每点击一次屏幕,生成现有三角形的内部三角形,重画屏幕
 */
public class Triangle {

	Point p1 , p2, p3;
	boolean isCenterT = false;
	
	public Triangle(Point p1, Point p2, Point p3) {
		this.p1 = p1;
		this.p2 = p2;
		this.p3 = p3;
	}
	
	public Triangle(Point p1, Point p2, Point p3, boolean isCenterT) {
		this.p1 = p1;
		this.p2 = p2;
		this.p3 = p3;
		this.isCenterT = isCenterT;
	}
	
	@SuppressWarnings("unchecked")
	public void createInner(List list)
	{
		Point m1 = this.getMiddle(p1, p2);
		Point m2 = this.getMiddle(p1, p3);
		Point m3 = this.getMiddle(p2, p3);
		list.add(new Triangle(m1, m2, m3, true));
		list.add(new Triangle(p1, m1, m2));
		list.add(new Triangle(p2, m1, m3));
		list.add(new Triangle(p3, m2, m3));
	}
	
	private Point getMiddle(Point p1, Point p2)
	{
		return new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
	}
	
	public void draw(Graphics g)
	{
		g.drawLine(p1.x, p1.y, p2.x, p2.y);
		g.drawLine(p1.x, p1.y, p3.x, p3.y);
		g.drawLine(p2.x, p2.y, p3.x, p3.y);
	}
	
	@SuppressWarnings("unchecked")
	static List list = new LinkedList();
	
	public static void main(String[] args) {
		
		int width = 400;
		int height = 400;
		
		//也可以在按键事件中再添加初始图像(最好是随机图形)
		Point p1 = new Point(width / 2, 20);
		Point p2 = new Point(20, height - 20);
		Point p3 = new Point(width - 20, height - 20);
		list.add(new Triangle(p1, p2, p3));
		
		JFrame frame = new JFrame("triangle");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JPanel panel = new JPanel()
		{
			@Override
			protected void paintComponent(Graphics g) {
				super.paintComponent(g);
				g.setColor(Color.black);
				for (int i = 0; i < list.size(); i++) {
					Triangle t = (Triangle)list.get(i);
					t.draw(g);
				}
			}
		};
		
		panel.addMouseListener(new MouseAdapter()
		{
			@SuppressWarnings("unchecked")
			@Override
			public void mouseClicked(MouseEvent e) {
				List list2 = new LinkedList();
				for (int i = 0; i < list.size(); i++) {
					Triangle t = (Triangle)list.get(i);
					if(t.isCenterT)continue;
					t.createInner(list2);
				}
				list.clear();
				list = list2;
				Component c = e.getComponent();
				c.repaint();
			}
		});
		panel.setFocusable(true);
		panel.setPreferredSize(new Dimension(width,height));
		frame.getContentPane().add(panel);
		frame.pack();
		
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}
	
}

posted on 2011-05-31 10:58  台哥编程课堂  阅读(248)  评论(0编辑  收藏  举报

导航