在java中绘制多个椭圆
问题描述:
我目前正在计划编写一些碰撞检测代码。但是,我遇到了一个问题。我想绘制的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,然后乘以它。 您的球体构造看起来应该像
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
谢谢你......其实我后来发现我错过了我的括号 –
答
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);
}
什么意思_“不工作” _ ?你期望什么,你的程序做什么? –
嗯,我的意思是球体没有在屏幕上绘制。只有一个空白窗口出现。 –
另请参见[使用复杂形状的碰撞检测](http://*.com/a/14575043/418556)。 –