很早前做的东西了,早就该发,一直忘记,今天终于想起来了,发上来吧。
代码如下:创建了两个类
第一个类:DrawBoard
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawBoard {
public static void main(String [] args){
DrawBoard db = new DrawBoard();
db.createboard();
}
public void createboard(){
JFrame jf = new JFrame();
jf.setSize(600, 600);
jf.setResizable(false);
jf.setTitle("套三角");
jf.setDefaultCloseOperation(3);
jf.setLayout(new FlowLayout());
jf.setVisible(true);
Graphics g = jf.getGraphics();
boardlistener lis = new boardlistener(g);
jf.addMouseListener(lis);
}
}
第二个类:BoardListener
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class BoardListener implements MouseListener{
Graphics g;
public BoardListener(Graphics g1){
g=g1;
}
public void mouseClicked(MouseEvent arg0) {
int x1=200,y1=400,x2=400,y2=400,x3=300,y3=227;
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
g.drawLine(x1, y1, x3, y3);
int x4=(x1+x3)/2;int x5=(x2+x1)/2;int x6=(x3+x2)/2;
int y4=(y1+y3)/2;int y5=(y2+y1)/2;int y6=(y3+y2)/2;
g.drawLine(x4, y4, x5, y5);
g.drawLine(x6, y6, x5, y5);
g.drawLine(x4, y4, x6, y6);
digui(x3,y3,x4,y4,x6,y6);
digui(x1,y1,x4,y4,x5,y5);
digui(x2,y2,x5,y5,x6,y6);
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
public void digui(int x1,int y1,int x2,int y2,int x3,int y3){
int m1,n1,m2,n2,m3,n3;
m1=(x1+x2)/2;m2=(x1+x3)/2;m3=(x2+x3)/2;
n1=(y1+y2)/2;n2=(y1+y3)/2;n3=(y2+y3)/2;
g.drawLine(m1, n1, m2, n2);
g.drawLine(m3, n3, m2, n2);
g.drawLine(m1, n1, m3, n3);
int p1=Math.abs(m2-m3);
int p2=Math.abs(m1-m3);
int p3=Math.abs(m1-m2);
if(p1<=10&&p2<=10&&p3<=10)
return;
else
digui(m1,n1,x2,y2,m3,n3);
digui(m2,n2,x3,y3,m3,n3);
digui(m1,n1,x1,y1,m2,n2);
}
}