import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JLabel;
public class Pentagram extends JLabel {
private static final long serialVersionUID = -3847465547528967067L;
private Point pointA;
private Point pointB;
private Point pointC;
private Point pointD;
private Point pointE;
private Point pointLeftInner;
private Point pointRightInner;
private int pix;
private static Color bgColor = Color.YELLOW;
private static Color fieldColor = Color.RED;
public static void setBgColor(Color bgColor) {
Pentagram.bgColor = bgColor;
}
public static void setFieldColor(Color fieldColor) {
Pentagram.fieldColor = fieldColor;
}
/**只有width有效,把label弄成正方的*/
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, width);
}
/**只有width有效,把label弄成正方的*/
public void setSize(int width, int height) {
super.setSize(width, width);
}
public void setSize(int size){
setSize(size, size);
}
public Pentagram(int size) {
pix = size/12;
setSize(pix*12);
initPoints();
}
private void initPoints() {
pointA = new Point(6*pix, 0); //上边中间点
pointB = new Point(0, 4*pix); //左边上面点
pointC = new Point(12*pix, 4*pix); //右边上面点
pointD = new Point(3*pix, 12*pix); //左边下面点
pointE = new Point(9*pix, 12*pix); //右边下面点
pointLeftInner = new Point(5*pix, 4*pix); //左边里面的点
pointRightInner = new Point(7*pix, 4*pix); //右边里面的点
}
private void draw(Graphics g) {
fillPolygon(g,pointA,pointLeftInner,pointRightInner);
fillPolygon(g,pointB,pointE,pointRightInner);
fillPolygon(g,pointC,pointD,pointLeftInner);
}
/**
* 已知点,填充多边形。
* @param g 画笔
* @param points 已知的'点'们
*/
private void fillPolygon(Graphics g,Point...points){
int[] xPoints = new int[points.length];
int[] yPoints = new int[points.length];
for (int i = 0; i < points.length; i++) {
xPoints[i] = points[i].x;
yPoints[i] = points[i].y;
}
g.fillPolygon(xPoints, yPoints, points.length);
}
public void paint(Graphics g) {
g.setColor(bgColor);
g.fillRect(0, 0, 12*pix, 12*pix);
g.setColor(fieldColor);
draw(g);
}
}
/**以下是测试代码*/
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(200, 200, 400, 400);
JLabel label = new Pentagram(frame.getSize().height/2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.setVisible(true);
}
}