之前的两个例子都是通过调用Graphics2D.draw方法绘制Shape接口的实现类,下面的示例将使用不同的方法来绘制另外两个基本形状--圆形和弧形。
1 public class MyTest extends JPanel {
2 public static void main(String args[]) {
3 JFrame f = new JFrame("Circle");
4 f.setSize(360, 300);
5 f.add(new MyTest());
6 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7 f.setLocationRelativeTo(null);
8 f.setVisible(true);
9 }
10 public MyTest() {
11 setBackground(Color.white);
12 setForeground(Color.white);
13 }
14 @Override
15 public void paintComponent(Graphics g) {
16 super.paintComponent(g);
17 g.setColor(Color.red);
18 paintCircle(g);
19 paintArc(g);
20 }
21 //画圆
22 private void paintCircle(Graphics g) {
23 Graphics2D g2 = (Graphics2D)g;
24 //没有提供drawCircle方法,通过将椭圆的width和heigh参数设置为等长,
25 //即可获得一个圆形。
26 g2.drawOval(5, 15, 75, 75);
27 }
28 private void paintArc(Graphics g) {
29 Graphics2D g2 = (Graphics2D) g;
30 int x = 50;
31 int y = 70;
32 g2.setStroke(new BasicStroke(8.0f));
33 //缺省填充为饼图
34 g2.fillArc(x, y, 200, 200, 90, 135);
35 //还可以通过Arc2D构造函数中的最后一个参数来定义不同的填充类型
36 Color oldColor = g.getColor();
37 g.setColor(Color.blue);
38 g2.fill(new Arc2D.Double(200, 30, 200, 200, 90, 135,Arc2D.CHORD));
39 g.setColor(oldColor);
40 }
41 }
4) 绘制多边形:
1 public class MyTest extends JPanel {
2 public static void main(String args[]) {
3 JFrame f = new JFrame("Polygon");
4 f.setSize(360, 300);
5 f.add(new MyTest());
6 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7 f.setLocationRelativeTo(null);
8 f.setVisible(true);
9 }
10 public MyTest() {
11 setBackground(Color.white);
12 setForeground(Color.white);
13 }
14 @Override
15 public void paintComponent(Graphics g) {
16 super.paintComponent(g);
17 g.setColor(Color.red);
18 paintPolygon(g);
19 paintGeneralPath(g);
20 }
21 // 绘制多边形
22 private void paintPolygon(Graphics g) {
23 Polygon p = new Polygon();
24 for (int i = 0; i < 5; i++) {
25 p.addPoint((int) (100 + 50 * Math.cos(i * 2 * Math.PI / 5)),
26 (int) (100 + 50 * Math.sin(i * 2 * Math.PI / 5)));
27 }
28 g.drawPolygon(p);
29 }
30 //通过GeneralPath的方式绘制多边形
31 private void paintGeneralPath(Graphics g) {
32 Random generator = new Random();
33 Point2D[] points = new Point2D[6];
34 for (int i = 0; i < 6; i++) {
35 double x = generator.nextDouble() * getWidth();
36 double y = generator.nextDouble() * getHeight();
37 points[i] = new Point2D.Double(x, y);
38 }
39
40 g.setColor(Color.red);
41