递归画三角形 --- 先画该三角,然后求三条边的中点,递归画三个小三角形。
运行结果:
代码:
package shiyan6;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JPanel;
public class Triangle extends JPanel{
private int n=0;
public void run(){
n++;
repaint();
}
protected void paintComponent(Graphics g){
g.setColor(Color.red);
super.paintComponent(g);
Point p1 = new Point(50,500);
Point p2 = new Point(550,500);
Point p3 = new Point(300,67);
display(g,n,p1,p2,p3);
}
private void display(Graphics g,int n,Point p1,Point p2,Point p3){
if (n>0){
g.drawLine(p1.x, p1.y, p2.x, p2.y);
g.drawLine(p1.x, p1.y, p3.x, p3.y);
g.drawLine(p3.x, p3.y, p2.x, p2.y);
Point p4 = getmid(p1,p2);
Point p5 = getmid(p1,p3);
Point p6 = getmid(p2,p3);
display(g,n-1,p1,p4,p5);
display(g,n-1,p2,p4,p6);
display(g,n-1,p3,p6,p5);
}
}
private Point getmid(Point p1,Point p2){
Point p = new Point();
p.x=(p1.x+p2.x)/2;
p.y=(p1.y+p2.y)/2;
return p;
}
}
package shiyan6;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class abcd extends JFrame{
private Triangle T = new Triangle();
private JButton jb = new JButton("Increase");
public abcd(){
this.add(T);
JPanel panel=new JPanel();
panel.add(jb);
this.add(panel,BorderLayout.SOUTH);
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
T.run();
}
});
}
public static void main(String[] args) {
abcd f = new abcd();
f.setTitle("思瑞平斯基三角");
f.setSize(600,600);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}