在 Java 中创建随机三角形

Creating random Triangles in Java

我需要创建一个程序来生成五个随机三角形,全部填充随机颜色。随着 window 的大小调整,三角形也必须重新绘制。问题是三角形根本没有出现,我只是得到一个灰色框。我觉得我遗漏了一些明显的东西,比如缺少导入或错误位置的一行,但我已经多次尝试调整代码但无济于事。我的 drawPolygon 数组都错了吗?我不知道 - 我真的需要一些帮助。

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.util.Random;
import java.awt.Color;
import java.awt.Point;
import javax.swing.JPanel;
import javax.swing.JFrame;

 class RandomTriangles extends JPanel {
     public void paint(Graphics g) {
         super.paintComponent(g);
         Graphics2D g2d = (Graphics2D) g;
         float strokeThickness = 2.0f;

        BasicStroke stroke = new BasicStroke(strokeThickness,
                BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
        g2d.setStroke(stroke);

        Random randGen = new Random();
        int curHeight = this.getHeight();
        int curWidth = this.getWidth();

        int [] x = new int [3];
        int [] y = new int [3];

        for(int i = 0; i < 3; i++) {
            x[i] = randGen(curWidth);
            y[i] = randGen(curHeight);
        }

        for(int t = 0; t < 5; t++){
            g2d.fillPolygon(x, y, 3);
            g2d.setColor(new Color(randGen.nextInt(256),      randGen.nextInt(256), randGen.nextInt(256)));
        }

    }

    private int randGen(int curWidth) {
        // TODO Auto-generated method stub
        return 0;
    }
}

public class Triangles {
     public static void main(String[] args) {
         new Triangles();
    }

        Triangles() {
        JFrame frame = new JFrame("Triangles");

        frame.add(new RandomTriangles());

        frame.setSize(500, 500);
        frame.setVisible(true);
    }

}

首先,您创建一个 Random 对象,这很好!

    Random randGen = new Random();

但是你从不使用它。相反,您调用 randGen,这是您定义的函数

    for(int i = 0; i < 3; i++) {
        x[i] = randGen(curWidth);
        y[i] = randGen(curHeight);
    }

但是 randGen 被定义为总是 return0!您应该删除该方法,并在循环调用中

    for(int i = 0; i < 3; i++) {
        x[i] = randGen.nextInt(curWidth);
        y[i] = randGen.nextInt(curHeight);
    }