2017-03-01 11 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

あなたはとてもintにランダムな値をキャストそれは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クラスのコンストラクタでは、ArrayListのオブジェクトをSphereに作成し、20個のオブジェクトをリストに追加する必要があります。

Sphereオブジェクトに塗りつぶす方法を知っているように、Sphereクラスにpaint(...)メソッドを追加する必要があります。あなたはArrayListを反復処理し、各Sphereをペイントする必要がpaintComponent(...)メソッドあなたのドロークラスで次に

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

:ような何か

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

    for (each sphere in the ArrayList) 
     sphere.paint(g); 
} 
関連する問題