import
java.awt.Color;
import
java.awt.Dimension;
import
java.awt.Graphics;
import
javax.swing.JFrame;
import
javax.swing.JPanel;
@author
public
class
Triangle extends
JPanel {
private
static
final
long
serialVersionUID =
6899161860200488093L
;
private
final
int
min =
8
;
private
final
int
insets =
25
;
private
int
color =
0
;
private
final
Color[] colors =
new
Color[]{
Color.red, Color.black, Color.blue}
;
public
Triangle
(){
super
();
setOpaque
(false
);
setBackground
(Color.white);
setPreferredSize
(new
Dimension
(800
,700
));
}
@return
private
int
getBaseSize
(){
return
getSize
().width -
(insets *
2
);
}
public
void
paint
(Graphics g) {
int
hauteur =
(int
)(getBaseSize
() *
Math.sqrt
(3
)/
2
);
int
xA =
insets;
int
xB =
insets +
getBaseSize
();
int
xC =
insets +
getBaseSize
() /
2
;
int
[] sommetsX =
{
xA, xB, xC}
;
int
yA =
insets +
hauteur;
int
yB =
insets +
hauteur;
int
yC =
insets;
int
[] sommetsY =
{
yA, yB, yC}
;
drawTriangle
(sommetsX, sommetsY, getBaseSize
() /
2
, g);
super
.paint
(g);
}
@param
@param
@param
@param
private
void
drawTriangle
(int
[] sommetsX, int
[] sommetsY, int
d , Graphics g) {
if
(d >
min) {
int
[] s1 =
{
2
, 2
, 1
}
;
int
[] s2 =
{
1
, 0
, 0
}
;
int
[] x =
{
(sommetsX[1
] +
sommetsX[2
]) /
2
,
(sommetsX[0
] +
sommetsX[2
]) /
2
,
(sommetsX[0
] +
sommetsX[1
]) /
2
}
;
int
[] y =
{
(sommetsY[1
] +
sommetsY[2
]) /
2
,
(sommetsY[0
] +
sommetsY[2
]) /
2
,
(sommetsY[0
] +
sommetsY[1
]) /
2
}
;
for
(int
i =
0
; i <
3
; i+
+
){
int
[] newX =
{
sommetsX[i], x[s1[i]], x[s2[i]]}
;
int
[] newY =
{
sommetsY[i], y[s1[i]], y[s2[i]]}
;
drawTriangle
(newX, newY, d /
2
, g);
}
}
else
{
g.setColor
(colors[color]);
g.fillPolygon
(sommetsX, sommetsY, 3
);
if
(color =
=
0
){
color =
1
;
}
else
if
(color =
=
1
){
color =
2
;
}
else
{
color =
0
;
}
}
}
public
static
void
main
(String[] args) {
JFrame frame =
new
JFrame
("
Triangle
de
sierpinski
"
);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.setContentPane
(new
Triangle
());
frame.pack
();
frame.setVisible
(true
);
}
}