2012-10-02 25 views
2

我在獲取java的swing和awt庫(第一次使用它們)以正確地爲我工作時遇到了一些麻煩。基本上,我想製作一個隨機生成的三角形,然後將其顯示在JPanel上。我一直在研究它,但似乎無法讓三角形顯示出來。創建一個隨機生成的三角形並將其繪製到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};等,我會得到一個三角形。

謝謝!

+1

使用paintComponent(...)不繪製(...)。 – LanguagesNamedAfterCofee

回答

4

確保沒有點在同一條線上的公式不能保證2點位於同一條線上。通常至少有2個共線點。您可以通過使用避免這種情況:

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

工作!但是,你能否簡要闡述它爲什麼起作用?我不認爲我完全理解。 –

4

您能否簡要爲什麼它的工作詳細點嗎?

謂詞p = ((x2 - x1) * (y3 - y1) == (y2 - y1) * (x3 - x1))true當三點collinear

您的while聲明while (!p)僅在找到三個共線點時才退出do循環。

相反,@Reimeus的聲明while (p)僅在找到有效的三角形時退出do循環。

+1

非常感謝! –