如何在java中填充多边形?
问题描述:
我有一个小问题..我实际上在做一个java程序(这是一个GUI)。 有一个名为Map的类,我在其中创建了一个地图..(或者至少我在尝试)。构造函数初始化地图,并返回一个Area,然后在View类中绘制它。我试着用g2.fillPolygon(x [],y [],n)来做这个经典的方法,但它不起作用。这里是源代码:如何在java中填充多边形?
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
}
这里是视图类:
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.
}
}
我会在这种情况下怎么办? 非常感谢。
答
就像Graphics2D#draw(Shape)
方法一样,有一个Graphics2D#fill(shape)
方法。
g2.setColor(Color.BLUE);
g2.fill(map.area);
g2.setColor(Color.RED);
g2.draw(map.area);
你可能想看看2D Graphics更多细节
+0
谢谢!!! :) – MArivs
对不起,我的语法。我写得很快。 – MArivs
注意:不要用已经被Java使用过的名称来命名你的类/类型,比如'Map'' List'' Set'' Object''Character'。 – Pshemo
我相信你需要一个传递给fillPolygon方法的Paint对象。并且该绘画对象将具有填充属性和颜色等。 – Batdude