【问题标题】:How to fill a polygon in java?如何在java中填充多边形?
【发布时间】:2016-02-12 23:14:43
【问题描述】:

我有一个小问题。我实际上是在用 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
}

这是视图类:

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.
}
}

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

【问题讨论】:

  • 对不起我的语法。我写得很快。
  • 旁注:不要使用 Java 已经使用的名称命名您的类/类型,例如 Map List Set Object Character
  • 我相信您需要将 Paint 对象传递给 fillPolygon 方法。并且该绘画对象将具有填充属性和颜色等。
  • 创建一个实际的Polygon 并通过它?

标签: java graphics


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多