// import necessary packages
import java.applet.*;
import java.awt.*;
import java.util.Random;
public class FirstApplet extends Applet implements Runnable
{
//position of the ball
int x_pos = 1;
int y_pos = 1;
int first_x =1;
int first_y =1;
//ball size
int radius = 5;
//direction
int x_speed = 1;
int y_speed = 1;
//applet size
int appletsize_top = 10;
int appletsize_bottom = 370;
int appletsize_left = 10;
int appletsize_right = 370;
//random movement
Random rnd = new Random ();
//Drawing image off screen
private Image dbImage;
private Graphics dbg;
int maxspeed = 1;
// start - method is called every time you enter the HTML
public void start ()
{
// define a new thread
Thread th = new Thread (this);
// start this thread
th.start ();
}
//run- start the applet game
public void run ()
{
while (true)
{
// lower ThreadPriority
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
//change direction if ball hits right side
if (x_pos > appletsize_left)
{
// Setzen der x - Position
x_pos += first_x;
y_pos += first_y;
x_speed = (rnd.nextInt ()) % maxspeed;
}
else if (x_pos < appletsize_right)
{
// Setzen der x - Position
x_pos += first_x;
y_pos += first_y;
x_speed = (rnd.nextInt ()) % maxspeed;
}
else if (y_pos > appletsize_top)
{
// Setzen der x - Position
x_pos += first_x;
y_pos += first_y;
x_speed = (rnd.nextInt ()) % maxspeed;
}
else if (y_pos < appletsize_bottom)
{
// Setzen der x - Position
x_pos += first_x;
y_pos += first_y;
x_speed = (rnd.nextInt ()) % maxspeed;
}
//repaint applet
repaint();
try
{
// Stop thread for the speed
Thread.sleep (10);
}
catch (InterruptedException ex)
{
}
// set ThreadPriority to maximum value
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
//create an image off screen and loads it into the applet
public void update (Graphics g)
{
// initialize buffer
if (dbImage == null)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
}
// clear screen in background
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbg.setColor (getForeground());
paint (dbg);
// draw image on the screen
g.drawImage (dbImage, 0, 0, this);
}
/** paint - method allows you to paint into your applet. This method is called e.g. if you move your browser window or if you call repaint() */
public void paint (Graphics g)
{
// set color
g.setColor (Color.red);
// paint a filled colored circle
g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
}
// Method to handle mouse down events
public boolean mouseDown (Event e, int x, int y)
{
// Change direction, put speed into a minus number 1 now become -1
x_speed = - (x_speed);
return true;
}
}