如何在java.awt.geom中初始化一个Area对象?

时间:2013-10-30 22:35:15

标签: java graphics geometry

java.awt.geom包在操作矢量图形时看起来非常有用,我对这个函数特别感兴趣:

public void add(Area rhs)

Adds the shape of the specified Area to the shape of this Area. The resulting shape of this Area will include the union of both shapes, or all areas that were contained in either this or the specified Area. 

 // Example:
 Area a1 = new Area([triangle 0,0 => 8,0 => 0,8]);
 Area a2 = new Area([triangle 0,0 => 8,0 => 8,8]);
 a1.add(a2);

    a1(before)     +         a2         =     a1(after)

 ################     ################     ################
 ##############         ##############     ################
 ############             ############     ################
 ##########                 ##########     ################
 ########                     ########     ################
 ######                         ######     ######    ######
 ####                             ####     ####        ####
 ##                                 ##     ##            ##

我是java的新手,所以请原谅我,如果我问一些愚蠢的东西,但是当我将代码粘贴到netbeans中时,它表示错误,说我应该在某处声明triangle。我不知道这种语法的本质,经过一些搜索后,我仍然不知道如何处理它。

1 个答案:

答案 0 :(得分:2)

这似乎是伪代码(概念图)而不是实际代码。

代码应如下所示:

import java.awt.Polygon;
import java.awt.geom.Area;

public class AreaAddition {

    public void addTriangles() {
        Polygon triangle1 = new Polygon();
        triangle1.addPoint(0, 0);
        triangle1.addPoint(8, 0);
        triangle1.addPoint(0, 8);

        Polygon triangle2 = new Polygon();
        triangle2.addPoint(0, 0);
        triangle2.addPoint(8, 0);
        triangle2.addPoint(8, 8);

        Area a1 = new Area(triangle1);
        Area a2 = new Area(triangle2);
        a1.add(a2);

        // Code that draws the Area belongs here.
    }

}

我遗漏了绘图部分,因为它非常重要,在我看来,它超出了“Java新手”的范围。

我建议您在http://docs.oracle.com/javase/tutorial/阅读Java教程(查找标题为“Trails Covering the Basics”的部分)。它们是学习Java的一种简单而自由的方式。