標籤:raw 幾何 for imp line height panel uid super
Java2D支援通過GeneralPath實現繪製任意的幾何形狀。
步驟:1)執行個體化GeneralPath對象
2)調用moveTo()方法錨地開始點座標
3)調用lineTo()或curveTo()方法繪製連接線
4)調用closePath()方法完成幾何形狀繪製
package chapter1;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.GeneralPath;
public class GeneralPathDemo extends JPanel {
private static final long serialVersionUID = 1L;
public GeneralPathDemo(){
super();
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
int x1 = this.getWidth()/5;
int y1 = this.getHeight()-20;
int x2 = this.getWidth()/2;
int y2 = 20;
int x3 = this.getWidth()-20;
int y3 = this.getHeight()-20;
int x4 = 20;
int y4 = this.getHeight()/3;
int x5 = this.getWidth()-20;
int y5 = y4;
int x1points[] = {x1,x2,x3,x4,x5};
int y1points[] = {y1,y2,y3,y4,y5};
g2d.setPaint(Color.RED);
GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,x1points.length);
polygon.moveTo(x1points[0],y1points[0]);
//順序畫下其他點
for(int i=1; i<x1points.length; i++){
polygon.lineTo(x1points[i],y1points[i]);
}
polygon.closePath();//調用closePath形成一個封閉幾何形狀
g2d.draw(polygon);//繪製
g2d.dispose();//釋放資源
}
public static void main(String args[]){
JFrame jf = new JFrame("Demo Graphics");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(new GeneralPathDemo(), BorderLayout.CENTER);
jf.setPreferredSize(new Dimension(380, 380));
jf.pack();
jf.setVisible(true);
}
}
Java——繪製五角星