Question on providing access to several objects
Hey All,
I am trying to make several balls moving within a rectangle and bouncing off the wall and other balls. I intended to make 5 balls(lines are below) but never make it show more than one. Please point out what goes wrong or suggest a solution. Thanks.
import java.awt.*;
import javax.swing.*;
import java.util.*;
publicclass moreBouncingBalls{
int diameter;
int deltaX;
int deltaY;
int x;
int y;
int r;
int g;
int b;
publicstaticvoid main(String[] args){
moreBouncingBalls BallA=new moreBouncingBalls();
moreBouncingBalls BallB=new moreBouncingBalls();
moreBouncingBalls BallC=new moreBouncingBalls();
moreBouncingBalls BallD=new moreBouncingBalls();
moreBouncingBalls BallE=new moreBouncingBalls();
BallA. setBall();
BallB. setBall();
BallC. setBall();
BallD. setBall();
BallE. setBall();
}
void setBall (){
Random random =new Random( );
deltaX = random.nextInt(100);
deltaY = random.nextInt(100);
r=random.nextInt(255);
g=random.nextInt(255);
b=random.nextInt(255);
diameter = 10+random.nextInt(41);
go();
}
void go(){
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel=new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
while(deltaX!=0&&deltaY!=0){
x=x+deltaX;
y=y+deltaY;
drawPanel.repaint();
try{Thread.sleep(50);
}
catch(Exception ex){}
if(x<=0||x+diameter>300){
deltaX=(deltaX)*(-1);
}
if(y<=0||y+diameter>300){
deltaY=(deltaY)*(-1);
}
}
}
class MyDrawPanelextends JPanel{
publicvoid paintComponent (Graphics a){
a.setColor(Color.white);
a.fillRect(0,0,this.getWidth(),this.getHeight());
a.setColor(new Color(r,g,b));
a.fillOval(x,y,diameter,diameter);
}
}
}

