hi guys,
i am working on a new java program, the program consists of a ball, bouncing around the applet, i have created button to control the ball, one to stop the ball bouncing, another to resume the ball boucing and another to reverse the direction of the ball bouncing,
but i am trying to re-design the buttons so that i can steer the direction of ball / drag the ball with the mouse around the applet.
the code so far is below...
any advice and help, would be appreciated a lot.....
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Bounce extends Applet implements Runnable {
int x_shift = 1;
int y_shift = 1;
Thread t;
boolean bouncing;
boolean testOutput = true;
Button
b1 = new Button("Start"),
b2 = new Button("Reverse Direction"),
b3 = new Button("Stop");
public void init() {
b1.addActionListener(new B1());
b2.addActionListener(new B2());
b3.addActionListener(new B3());
add(b1);
add(b2);
add(b3);
r = new Rectangle(30,50,20,20);
t = new Thread(this);
t.start();// behaviour of thread controlled by run method
bouncing = true;
}
public void paint(Graphics g) {
if (bouncing) g.setColor(Color.blue);
else g.setColor(Color.red);
g.fillOval(r.x,r.y,r.width,r.height);
if (testOutput)
System.out.println ("x = " + r.x + " y = " + r.y + " bouncing = " + bouncing);
}
class B1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
t.resume();
bouncing = true;
getAppletContext().showStatus("Start pressed");
}
}
class B2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!bouncing)
t.suspend();
bouncing = true;
y_shift *= -1;
x_shift *= -1;
getAppletContext().showStatus("Reverse Direction pressed");
}
}
class B3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!bouncing)
System.exit(1);
t.suspend();
bouncing = false;
x_shift *= -1;
getAppletContext().showStatus("Stop pressed");
}
}
public void update(Graphics g) {
Image offScreenImage = createImage(getSize().width, getSize().height);
paint(offScreenImage.getGraphics());
g.drawImage(offScreenImage,0,0, null);
}
public void run() {
while (true) { // Thread performs endless loop
r.x += x_shift;
r.y += y_shift;
if (r.x>= getSize().width || r.x < 0) {
x_shift *= -1;
}
if (r.y>= getSize().height || r.y < 40) { // Why 40?
y_shift *= -1;
}
repaint();
try {
Thread.currentThread().sleep(2);
}
catch (Exception e) {
}
}
}
private Rectangle r;
public boolean mouseDown(Event e) {
return true;
}
public boolean mouseDrag(Event e ) {
return true;
}
public boolean mouseUp(Event e) {
return true;
}
}
thx for your time,
tc..