This program extends the Bouncing Ball program by having multiple instances of the ball object.
![[bouncingballs.png]]
# GUIBall Main Class
```java
package guiball;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GUIBall extends JFrame implements ActionListener {
final int NUMBERBALLS = 10;
Ball[] balls = new Ball[NUMBERBALLS];
int height;
int width;
GUIBall() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(640, 480);
this.setLocationRelativeTo(null);
this.getContentPane().add(panel);
this.setVisible(true);
height = this.getContentPane().getHeight();
width = this.getContentPane().getWidth();
System.out.println(width);
System.out.println(height);
// Instantiate balls
//Math.random()*4 - 2 gives random number -1,0,1
for (int i = 0; i < NUMBERBALLS; i++) {
balls[i] = new Ball((int) (Math.random() * width), (int) (Math.random() * height), (int) (Math.random() * 4 - 2), (int) (Math.random() * 4 - 2));
}
balls[1].print();
balls[0].setField(width, height);
Timer timer = new Timer(10, this);
timer.start();
}
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Ball ball : balls) {
ball.move();
ball.draw(g2);
}
}
};
public static void main(String[] args) {
// TODO code application logic here
new GUIBall();
}
@Override
public void actionPerformed(ActionEvent ae) {
panel.repaint();
}
}
```
# Ball Class
```java
package guiball;
import java.awt.Graphics2D;
public class Ball {
protected int x;
protected int y;
protected int xVect;
protected int yVect;
protected static int ballRadius = 30;
protected static int fieldHeight;
protected static int fieldWidth;
Ball(int x, int y, int xVect, int yVect) {
this.x = x;
this.y = y;
this.xVect = xVect;
this.yVect = yVect;
}
public void setField(int width, int height) {
this.fieldWidth = width;
this.fieldHeight = height;
}
public void move() {
if (y > fieldHeight - ballRadius || y < 0) {
yVect = -yVect;
}
if (x > fieldWidth - ballRadius || x < 0) {
xVect = -xVect;
}
x += xVect;
y += yVect;
}
public void draw(Graphics2D g2) {
g2.fillOval(x, y, ballRadius, ballRadius);
}
public void print() {
System.out.println("x: " + x + " y: " + y + " xVect: " + xVect + " yVert: " + yVect);
}
}
```
Can you add collision detection?