简体   繁体   中英

Polygon shape does not show up in Java

I'm trying to make some shapes with Java, I created two rectangles and they show up normally, but lately I integrated a polygon shape code but it not showing up while running the program. Somebody help in this please!

Here is a screenshot after running:

在此处输入图片说明

Here is the code I use:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class shapes extends JPanel{
int midX = 120;
int midY = 60;
int radius[] = {118,40,90,40};
int nPoints = 16;
int[] X = new int[nPoints];
int[] Y = new int[nPoints];
int i;
double max;

public void paintComponent(Graphics gphcs){
super.paintComponent(gphcs);
this.setBackground(Color.WHITE);

gphcs.setColor(Color.BLUE);
gphcs.fillRect(25,25,100,30);

gphcs.setColor(Color.GRAY);
gphcs.fillRect(25,65,100,30);

gphcs.setColor(new Color(190,81,215));
gphcs.drawString("This is my text", 25, 120);

for (double current=0.0; i<nPoints; i++)
{
    double x = Math.cos(current*((2*Math.PI)/max))*radius[i % 4];
    double y = Math.sin(current*((2*Math.PI)/max))*radius[i % 4];

    X[i] = (int) x+midX;
    Y[i] = (int) y+midY;
}
gphcs.setColor(Color.RED);
gphcs.fillPolygon(X, Y, nPoints);
}
}

Acutally I wanted the polygon to show up as a star shape but it even didn't appear at all!

Thank you..

All your polygon co-ordinates are the same. Try

for (int i=0; i < nPoints; i++) {
   double x = Math.cos(i * ((2 * Math.PI) / nPoints)) * radius[i % 4];
   double y = Math.sin(i * ((2 * Math.PI) / nPoints)) * radius[i % 4];

   X[i] = (int) x + midX;
   Y[i] = (int) y + midY;
}

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