35 Graphics2D g2 = (Graphics2D) g;
36 for (int i = 0; i < points.length; i++) {
37 double x = points[i].getX() - 10 / 2;
38 double y = points[i].getY() - 10 / 2;
39 g2.fill(new Rectangle2D.Double(x, y, 10, 10));
40 }
41 Shape s = new QuadCurve2D.Double(points[0].getX(), points[0].getY(),
42 points[1].getX(), points[1].getY(), points[2].getX(),
43 points[2].getY());
44 g2.draw(s);
45 }
46
47 // 绘制三次曲线
48 private void paintCubicCurve(Graphics g) {
49 Random generator = new Random();
50 Point2D[] points = new Point2D[4];
51 //三次曲线的x坐标均大于getWidth()/2,因此可以显示在JPanel右侧。
52 for (int i = 0; i < 4; i++) {
53 double x = generator.nextDouble() * getWidth() / 2 + getWidth() / 2;
54 double y = generator.nextDouble() * getHeight();
55 points[i] = new Point2D.Double(x, y);
56 }
57 g.setColor(Color.red);
58 Graphics2D g2 = (Graphics2D) g;
59 for (int i = 0; i < points.length; i++) {
60 double x = points[i].getX() - 10 / 2;
61 double y = points[i].getY() - 10 / 2;
62 g2.fill(new Rectangle2D.Double(x, y, 10, 10));
63 }
64 Shape s = new CubicCurve2D.Double(points[0].getX(), points[0].getY(),
65 points[1].getX(), points[1].getY(), points[2].getX(),
66 points[2].getY(), points[3].getX(), points[3].getY());
67 g2.draw(s);
68 }
69 }
2. 区域(Area):
Java 2D支持4中几何图形区域计算方式,分别是add、substract、intersect和exclusiveOr。
add:组合区域包含了所有位于第一个区域或第二个区域内的点;
substract:组合区域包含了所有位于第一个区域内的点,但是不包括任何位于第二个区域内的点;
intersect:组合区域既包含了所有位于第一个区域内的点,又包含了所有位于第二个区域内的点;
exclusiveOr:组合区域包含了所有位于第一个区域内,或者是位于第二个区域内的所有点,但是这些点不能同时位于两个区域内。
下面的示例代码绘制了两个区域的四种不同组合方式。
1 public class MyTest extends JPanel {
2 public static void main(String args[]) {
3 JFrame f = new JFrame("Area Demo");
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 //横向和纵向各画一条分隔线,将JPanel的区域划分4个等份。
18 //然后在4个区间中画出四种不同的Area组合方式
19 int x = getWidth() / 2;
20 int y = getHeight() / 2;
21 g.setColor(Color.black);
22 g.drawLine(x, 0, x, getHeight());
23 g.drawLine(0, y, getWidth(), y);
24 paintArea(g);
25 }
26 private void paintArea(Graphics g) {
27 //1. 以add的方式组合两个Area,并绘制在JPanel的左上角
28 Shape sOne = new Ellipse2D.Double(40, 20, 80, 80);
29 Shape sTwo = new Rectangle2D.Double(60, 40, 80, 80);
30 Area areaOne = new Area(sOne);
31 Area areaTwo = new Area