2017-03-01 131 views
0

我目前正在計劃編寫一些碰撞檢測代碼。但是,我遇到了一個問題。我想繪製的JFrame窗口上的多個領域,但下面的代碼是不工作...請幫我... 這是我的代碼: -在java中繪製多個橢圓

import javax.swing.*; 
    import java.awt.*; 
    class Draw extends JPanel 
    { 
     public void paintComponent(Graphics g) 
     { 
      super.paintComponent(g); 
      for(int i=0;i<20;i++) 
       drawing(g,new Sphere()); 
     } 
     public void drawing(Graphics g,Sphere s) 
     { 
      g.setColor(s.color); 
      g.fillOval(s.x,s.y,s.radius*2,s.radius*2); 
     } 
     public static void main(String args[]) 
     { 
      JFrame jf = new JFrame("Renderer"); 
      jf.getContentPane().add(new Draw(),BorderLayout.CENTER); 
      jf.setBounds(100,100,400,300); 
      jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      jf.setVisible(true); 
     } 
    } 
    class Sphere 
    { 
     int x; 
     int y; 
     int radius; 
     Color color; 
     public Sphere() 
     { 
      this.x = (int)Math.random()*100; 
      this.y = (int)Math.random()*100; 
      this.radius = (int)Math.random()*20; 
      this.color = new Color((int)(Math.random()*255), 
    (int)(Math.random()*255),(int)(Math.random()*255)); 
     } 
    } 
+0

什麼意思_「不工作」 _ ?你期望什麼,你的程序做什麼? –

+0

嗯,我的意思是球體沒有在屏幕上繪製。只有一個空白窗口出現。 –

+0

另請參見[使用複雜形狀的碰撞檢測](http://stackoverflow.com/a/14575043/418556)。 –

回答

3

你施放的隨機值來詮釋這樣它是0,然後乘以它。 您的球體構造看起來應該像

public Sphere() { 
     this.x = (int) (Math.random() * 100); // cast the result to int not the random 
     this.y = (int) (Math.random() * 100); 
     this.radius = (int) (Math.random() * 20); 
     this.color = new Color((int) ((Math.random() * 255)), (int) (Math.random() * 255), (int) (Math.random() * 255)); 
} 
+0

謝謝你......其實我後來發現我錯過了我的括號 –

1
for(int i=0;i<20;i++) 
    drawing(g,new Sphere()); 

一幅畫方法僅適用於繪畫。

您不應該在paintComponent()方法中創建Sphere對象。 Swing重新繪製面板時無法控制。

相反,在您的Draw類的構造函數中,您需要創建Sphere對象的ArrayList,並將20個對象添加到列表中。

然後,您需要爲您的Sphere類添加一個paint(...)方法,以便Sphere對象知道如何繪製自己。喜歡的東西:

public void paint(Graphics g) 
{ 
    g.setColor(color); 
    g.fillOval(x, y, width, height) // 
} 

然後在你的繪圖類,你需要通過ArrayList迭代和油漆的paintComponent(...)方法每個Sphere

@Override 
protected void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 

    for (each sphere in the ArrayList) 
     sphere.paint(g); 
}