【问题标题】:Drawing multiple ovals in java在java中绘制多个椭圆
【发布时间】:2017-07-20 18:40:37
【问题描述】:

我目前正计划编写一些用于碰撞检测的代码。但是,我遇到了一个问题。我想在 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));
        }
    }

【问题讨论】:

  • “不工作”是什么意思?你期望什么,你的程序做什么?
  • 好吧,我的意思是球体根本没有在屏幕上绘制。只出现一个空白窗口。

标签: java swing


【解决方案1】:

您将随机值转换为 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));
}

【讨论】:

  • 谢谢哥们...实际上我后来发现我的括号不见了
【解决方案2】:
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) //
}

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

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

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

【讨论】:

    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多