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

Tay*_*yre 2 java random geometry swing 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,我有了一个扩展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(); 
  }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Rei*_*eus 5

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

   ...
   } while (((x2 - x1) * (y3 - y1) == (y2 - y1) * (x3 - x1)));
Run Code Online (Sandbox Code Playgroud)