java - 创建一个随机生成的三角形并将其绘制到 Jpanel

标签 java swing random geometry awt

我在让 java 的 swing 和 awt 库(第一次使用它们)正常工作时遇到了一些大麻烦。基本上,我想制作一个随机生成的三角形,然后将其显示在 JPanel 上。我已经研究了一段时间了,但我似乎无法让三角形显示出来。

我有一个 RandomTriangle 类,如下所示:

import java.util.*;
import java.math.*;

public class RandomTriangle {

  private Random rand = new Random();

  private int x1, y1,     // Coordinates
              x2, y2,
              x3, y3;
  private double a, b, c; // Sides

  public RandomTriangle(int limit) {
    do { // make sure that no points are on the same line
      x1 = rand.nextInt(limit);
      y1 = rand.nextInt(limit);

      x2 = rand.nextInt(limit);
      y2 = rand.nextInt(limit);

      x3 = rand.nextInt(limit);
      y3 = rand.nextInt(limit);
    } while (!((x2 - x1) * (y3 - y1) == (y2 - y1) * (x3 - x1)));

    a = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
    b = Math.sqrt(Math.pow((x3 - x2), 2) + Math.pow((y3 - y2), 2));
    c = Math.sqrt(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2));
  }


  public int[] getXCoordinates() {
    int[] coordinates = {this.x1, this.x2, this.x3};
    return coordinates;
  }

  public int[] getYCoordinates() {
    int[] coordinates = {this.y1, this.y2, this.y3};
    return coordinates;
  }
}

然后我有一个扩展 JPanel 的 SimpleTriangles 类:

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

public class SimpleTriangles extends JPanel {

  public SimpleTriangles() {
    JFrame frame = new JFrame("Draw triangle in JPanel");  
    frame.add(this);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    frame.setSize(400,400);  
    frame.setLocationRelativeTo(null);  
    frame.setVisible(true);  
  }

  public void paint(Graphics g) {
    super.paint( g );
    RandomTriangle myTriangle = new RandomTriangle(150);
    int[] x = myTriangle.getXCoordinates();
    int[] y = myTriangle.getYCoordinates();

    g.setColor(new Color(255,192,0));
    g.fillPolygon(x, y, 3);
  }

  public static void main(String[] args) {
    RandomTriangle myTriangle = new RandomTriangle(300);
    for (int x : myTriangle.getXCoordinates())
      System.out.println(x);
    for (int y : myTriangle.getYCoordinates())
      System.out.println(y);

    SimpleTriangles st = new SimpleTriangles(); 
  }
}

我做错了什么吗?就像我说的,这是我第一次用 Java 来搞乱 GUI,所以我可能过得很好。当我运行这个程序时,我得到一个灰色的空白 JPanel。但是,如果我明确指定坐标,例如 int[]x={0,150,300}; 等,我会得到一个三角形。

谢谢!

最佳答案

确保没有点在同一条线上的公式并不能确保 2 个点位于同一条线上。通常至少有 2 个共线点。您可以通过使用以下方法来避免这种情况:

   ...
   } while (((x2 - x1) * (y3 - y1) == (y2 - y1) * (x3 - x1)));

关于java - 创建一个随机生成的三角形并将其绘制到 Jpanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12699528/

相关文章:

java - 将新数据推送到 Firebase 数据库时设置自定义键

java - 循环获取选定的索引

java - 如何防止 JSlider 全范围移动?

python - 在 pandas 中对整个 DataFrame 进行采样时,避免连续列中出现两个相同的值

java - 如何在 Java 中解析包含 Μαϊ(希腊五月)的日期字符串

java - Spring MVC Rest 中的单元测试 - 转换问题

java - 从 jTextField 到表 sql 的查询插入错误

python - 抛硬币、随机变量的算法和 PyMC3

c - 在函数内声明 struct timeval time

java - 何时使用多个主要方法?