Search code examples
javagraphicsdrawingpolygonjava-2d

How to create Graphics object for drawing Polygon?


I need to draw a Polygon - by connecting consecutive points and then connecting the last point to the first.

With this goal I tried to use drawPolygon(xPoints, yPoints, nPoints). To my mind it's much more convenience approach to achieve this aim

But the Graphics class is abstract class and I we can't create instance object and call drawPolygon() method?

Code:

public void draw() {
        Graphics g = null;
        int xPoints [] = new int[pointsList.size()];
        int yPoints [] = new int[pointsList.size()];
        int nPoints = pointsList.size();

        for (int i = 0; i < pointsList.size(); i++) {
            xPoints [i] = (int) pointsList.get(i).getX();
            yPoints [i] = (int) pointsList.get(i).getY();
        } 

        g.drawPolygon(xPoints, yPoints, nPoints);
    }
  • Can we circumvent calling this method at any way?
  • Maybe exist some other ways to achieve this aim?

Solution

  • I have had the same problem, this was how I circumvented it:

    //assuming you are displaying your polygon in a JFrame with a JPanel
    public class SomeDrawingFrame extends JPanel{
        SomeDrawingFrame(){
        }
    
        @Override   //JFrame has this method that must be overwritten in order to 
                      display a rendered drawing.
    
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Polygon square = new Polygon();
    
            // these points will draw a square
            square.addPoint((0, 0));    //use this.getWidth() method if you want to 
                                             create based on screen size
            square.addPoint((0, 100));
            square.addPoint((100, 100));
            square.addPoint((100, 0)); 
            int y1Points[] = {0, 0, 100, 100};
    
            g.draw(polygon);
        }
    }
    

    now just create an instance of this and add it to a JFrame of minimum height and width of 100 each. You can use JFrame's getWidth() method which will return the size of the JFrame and use this to set your points instead (which is better) because then the image will render relative to the size of the frame itself.