在java中绘制多个椭圆

时间:2017-03-01 12:25:59

标签: java swing

我目前正计划编写一些碰撞检测代码。但是,我遇到了一个问题。我想在JFrame窗口上绘制多个球体,但以下代码不起作用...请帮助我... 这是我的代码: -

    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));
        }
    }

2 个答案:

答案 0 :(得分:3)

将随机值转换为int,使其为0,然后将其相乘。 您的Sphere构造函数应该看起来像

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));
}

答案 1 :(得分:1)

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

绘画方法仅适用于绘画。

您不应该在paintComponent()方法中创建Sphere对象。当Swing重新绘制面板时,您无法控制。

相反,在Draw类的构造函数中,您需要创建ArrayListSphere个对象,然后将20个对象添加到列表中。

然后,您需要向Sphere类添加paint(...)方法,以便Sphere对象知道如何绘制自己。类似的东西:

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

然后在您的Draw类的paintComponent(...)方法中,您需要遍历ArrayList并绘制每个Sphere

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

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