public class Ball implements Runnable{
int x = 10, y = 35;
int speed = 50;
Color color;
public Ball(int x, int speed, Color color){
this.x = x;
this.speed = speed;
this.color = color;
}
public void paint(Graphics g){
g.setColor(color);
g.fillOval(x, y, 50, 50);
}
@Override
public void run() {
while((y+10) <= 400){
y = y + 10;
try{
Thread.sleep(speed);
} catch (Exception e){
System.out.println("Message " + e);
}
}
}
}
Java Class
Shoot.java
public class Shoot implements Runnable{
int x = 10, y = 400;
public Shoot(int x){
this.x = x;
}
public void paint(Graphics g){
g.setColor(Color.ORANGE);
g.fillRect(x, y, 10, 20);
}
@Override
public void run() {
while(y-10 >= 10){
y = y-10;
try{
Thread.sleep(100);
} catch (Exception e){
System.out.println("Message : " + e);
}
}
}
}
JFrame Form
BallGame.java
public class BallGame extends javax.swing.JFrame implements Runnable, KeyListener{
Ball[] ball = new Ball[5];
int[] sball = {10, 100, 400, 300, 200};
int[] speedBall = {100, 100, 100, 100 ,100};
Color[] colorBall = {Color.BLACK, Color.BLUE, Color.RED, Color.GREEN, Color.MAGENTA};
Thread thread;
int x = 10;
Shoot shoot;
public BallGame() {
initComponents();
thread = new Thread(this);
thread.start();
for(int i = 0; i < 5; i++){
ball[i] = new Ball(sball[i], speedBall[i], colorBall[i]);
new Thread(ball[i]).start();
}
this.addKeyListener(this);
}
public void paint(Graphics g){
super.setSize(500, 500);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.fillRect(x, 445, 50, 50);
for(int i = 0; i < ball.length; i++){
if(ball[i] != null){
ball[i].paint(g);
}
}
shoot.paint(g);
}
@Override
public void run() {
while(true){
try{
Thread.sleep(100);
} catch (Exception e){
System.out.println("Message " + e);
}
for(int i = 0; i < ball.length; i++){
if(ball[i] != null && ball[i].y + 10 >= 400) {
ball[i] = null;
}
}
repaint();
}
}
@Override
public void keyPressed(KeyEvent ke) {
switch(ke.getKeyCode()){
case 37 : // Left
if(x - 10 >= 10) x = x - 10;
repaint();
break;
case 39 : // Right
if(x + 10 <= 400) x = x + 10;
repaint();
break;
case 32 : // Spcace
shoot = new Shoot(x+20);
new Thread(shoot).start();
break;
}
}
}