Marc L.
Marc L.

Reputation: 68

Draw Polygon within Panel of Swing GUI Java

I am trying to figure out how to use DrawPolygon within a Panel of a Swing GUI while learning the basics of Java GUI.

This is the code for generating the panel of the Swing GUI:

polygonArea = new javax.swing.JPanel(){
       protected void poly(Graphics g) {
      int xpoints[] = {35, 10, 25, 60, 20};
int ypoints[] = {105, 25, 5, 105, 25};
int xpoints2[] = {60, 70, 92, 80, 82};
int ypoints2[] = {105, 25, 5, 105, 25};
int xpoints3[] = {102, 98, 145, 107};
int ypoints3[] = {5, 105, 105, 100};
int npoints = 5;
int npointsl = 4;

g.fillPolygon(xpoints, ypoints, npoints);
g.fillPolygon(xpoints2, ypoints2, npoints);
g.fillPolygon(xpoints3, ypoints3, npointsl);
      }
    };
    polygonArea.setBackground(new java.awt.Color(240, 240, 240));

Based off generated GUI from Netbeans. I am really new to Java, but when I launch the file it appears like this:

enter image description here

https://i.sstatic.net/4KsIo.jpg

Instead of the poly function on its own which displays:

enter image description here

https://i.sstatic.net/XrAsK.png

Sorry if it's a pretty obvious error, any help would be much appreciated!

(Can't post images due to reputation)

Upvotes: 0

Views: 1643

Answers (2)

Reimeus
Reimeus

Reputation: 159754

The method poly is not invoked automatically in the paint stack in Swing. You need to do this explicitly for example

class PolyPanel extends JPanel {
    protected void poly(Graphics g) {
       ...  
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        poly(g);
    }
}

Upvotes: 4

Sourabh Bhat
Sourabh Bhat

Reputation: 1893

Override the function from JPanel, paintComponent(Graphics g) and call poly(Graphics g) from it. Something like this:

public void paintComponent(Graphics g) {
   super.paintComponent(g);
   poly(g);
}

Upvotes: 0

Related Questions