gpt4 book ai didi

java - 如何在Java中制作星形?

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:21 25 4
gpt4 key购买 nike

我正在尝试使用 Java 制作一些形状。我创建了两个具有两种不同颜色的矩形,但我想创建一个星形,但找不到有用的资源来帮助我完成此操作。

这是我的代码:

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

public class shapes extends JPanel{

@Override
public void paintComponent(Graphics GPHCS){
super.paintComponent(GPHCS);

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);
}
}

最佳答案

您可以尝试使用多边形和一些基本数学:

    int midX = 500;
int midY = 340;
int radius[] = {118,40,90,40};
int nPoints = 16;
int[] X = new int[nPoints];
int[] Y = new int[nPoints];

for (double current=0.0; current<nPoints; current++)
{
int i = (int) current;
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;
}

g.setColor(Color.WHITE);
g.fillPolygon(X, Y, nPoints);

关于java - 如何在Java中制作星形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16327588/

25 4 0
文章推荐: Java 将 列表转换到它的接口(interface)