简体   繁体   中英

How to fill a polygon in java?

I have one little problem.. I am actually doing a program in java (it's a GUI). There is one class named Map that in which I creat a map..(or atleast I am trying).The constructor initializes the map and it gives back an Area and I paint it in the View class. I tried the classical way to do it with g2.fillPolygon(x[],y[],n) but it does not works. Here is the source code:

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
}

Here is the View class:

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

What shall I do in this case? Thank you very much.

Just like the Graphics2D#draw(Shape) method, there is a Graphics2D#fill(shape) method.

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

You might like to have a look at 2D Graphics for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM