Hello,
I am relatively new to Java. I would like to know how to add additional threads to this applet. Particularly adding additional balls that bounce at the same time. I think the problem lies in my mousePressed event. The program will start a new ball, but make the existing ball disappear. Any help would be greatly appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Ball extends JApplet implements Runnable, MouseListener {
private Thread[] blueBall = new Thread[MAX_BALL_COUNT];
private boolean xUp, yUp, bouncing;
private int x, y, xDx, yDy;
int ballcount = 0;
final private static int MAX_BALL_COUNT = 20;
//init is called by the browser to inform the applet that Ball has been loaded
public void init()
{
xUp = false;
yUp = false;
xDx = 1;
yDy = 1;
addMouseListener( this );
bouncing = false;
}
public void mousePressed( MouseEvent e )
{
if ( ballcount < MAX_BALL_COUNT ) {
x = e.getX(); //PB: get the X position
y = e.getY(); //PB: get the Y position
blueBall[ballcount] = new Thread( this );
bouncing = true;
blueBall[ballcount].start();
ballcount++;
}
}
public void stop()
{
if ( blueBall != null )
blueBall = null;
}
public void start ()
{
for(int i = 0; i < blueBall.length; i++)
if(blueBall[i] != null)
blueBall[i].start();
}
public void paint( Graphics g )
{
super.paint( g );
if ( bouncing ) {
g.setColor( Color.blue );
g.fillOval( x, y, 10, 10 );
}
}
public void run()
{
while ( true ) {
try {
Thread.sleep( 100 );
}
// PB: process exception during sleep
catch ( Exception e ) {
System.err.println( "Exception: " + e.toString() );
}
if ( xUp == true )
x += xDx;
else
x -= xDx;
if ( yUp == true )
y += yDy;
else
y -= yDy;
if ( y <= 0 ) {
yUp = true;
yDy = ( int ) ( Math.random() * 5 + 2 );
}
else if ( y >= 190 ) {
yDy = ( int ) ( Math.random() * 5 + 2 );
yUp = false;
}
if ( x <= 0 ) {
xUp = true;
xDx = ( int ) ( Math.random() * 5 + 2 );
}
else if ( x >= 190 ) {
xUp = false;
xDx = ( int ) ( Math.random() * 5 + 2 );
}
repaint();
}
}
public void mouseExited( MouseEvent e ) {}
public void mouseClicked( MouseEvent e ) {}
public void mouseReleased( MouseEvent e ) {}
public void mouseEntered( MouseEvent e ) {}
}