2

我在让 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};等,我会得到一个三角形。

谢谢!

4

2 回答 2

5

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

   ...
   } while (((x2 - x1) * (y3 - y1) == (y2 - y1) * (x3 - x1)));
于 2012-10-02T23:17:23.190 回答
4

您能否简要说明它为什么起作用?

谓词p = ((x2 - x1) * (y3 - y1) == (y2 - y1) * (x3 - x1))true当三个点共线时。

仅当找到三个共线点时,您的while语句才会while (!p)退出循环。do

相反,@Reimeus 的语句仅在找到有效三角形时才while (p)退出循环。do

于 2012-10-03T04:54:44.487 回答