如何在java中填充多边形?

时间:2016-02-12 23:14:43

标签: java graphics

我有一个小问题..我实际上在java中做一个程序(它是一个GUI)。 有一个名为Map的类,我在其中创建了一个地图..(或至少我正在尝试)。构造函数初始化地图并返回一个区域,然后在View类中绘制它。我尝试用g2.fillPolygon(x [],y [],n)来实现它的经典方法,但它不起作用。这是源代码:

public class Map{
    Area area;
    //...
    public Map(){
        this.area=new Area(new Polygon(
                arrayX(),//ArrayY() and arrayX() are methods that generate     arrays with random numbers
                arrayY(),
                MAX
                ));
   }

//...stuff
}

以下是View类:

public class View extends JComponent{
    Map map=new Map();

//...stuff

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
//.......

    g2.draw(map.area);//this draws the normal polygon NOT filled
    g2.fillPolygon(map.ArrayX,map.arrayY,map.MAX);//this might fill the polygon but it does noot
    g2.fillPolygon(map.area);//this does not work (ofcourse) because it wants a Polygon type parameter. I tried to cast it but it still does not work.
}
}

在这种情况下我该怎么办? 非常感谢你。

1 个答案:

答案 0 :(得分:2)

Graphics2D#draw(Shape)方法一样,有Graphics2D#fill(shape)方法。

g2.setColor(Color.BLUE);
g2.fill(map.area);
g2.setColor(Color.RED);
g2.draw(map.area);

您可能希望查看2D Graphics了解更多详情