This is my code so far
Driver
class BallDriver extends Thread
{
public static void main(String[] args)
{
Bounce app = new Bounce();
//Ball ball = new Ball();
//Thread t = new Thread(app);
}
}
Bounce Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Bounce extends JFrame implements MouseListener
{
private JPanel canvas;
private JPanel buttonPanel;
private Ball ball;
private int x=0, y=0, xCoord, yCoord;
public Bounce()
{
setTitle("Bounce");
Container contentPane = getContentPane();
canvas = new JPanel();
contentPane.add(canvas, "Center");
buttonPanel = new JPanel();
LineBorder line = new LineBorder(Color.black);
buttonPanel.setBorder(line);
contentPane.add(buttonPanel, "South");
setSize(300, 300);
setVisible(true);
canvas.addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
ball = new Ball(canvas); // create a ball
//Thread t = new Thread(ball);
//t.start();
//gets co ordinates from where mouse is clicked
x = e.getX();
y = e.getY();
//gives co ordinates to ball object
ball.setXCoord(x);
ball.setYCoord(y);
ball.bounce();
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
} // end class Bounce
Ball Class
import java.awt.*;
import javax.swing.*;
public class Ball implements Runnable
{
private JPanel box;
private static final int XSIZE = 20;
private static final int YSIZE = 20;
private int x = 0;
private int y = 0;
private int dx = 2;
private int dy = 2;
public Ball(JPanel b)
{
box = b;
}//end Ball
public void setXCoord(int XIn)
{x=XIn;}// end setXCoord
public void setYCoord(int YIn)
{y=YIn;}// end setYCoord
public void draw()
{
Graphics g = box.getGraphics();
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose();
}//end draw
public void move()
{
Graphics g = box.getGraphics();
g.clearRect(x, y, XSIZE, YSIZE);
x += dx;
y += dy;
Dimension d = box.getSize();
if (x < 0)
{
x = 0; dx = -dx;
}
if (x + XSIZE >= d.width)
{
x = d.width - XSIZE; dx = -dx;
}
if (y < 0)
{
y = 0; dy = -dy;
}
if (y + YSIZE >= d.height)
{
y = d.height - YSIZE; dy = -dy;
}
g.setColor(Color.red);
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose();
}//end move
public void bounce()
{
draw();
for (int i = 1; i <= 1000; i++)
{
move();
try
{
Thread.sleep(5);
}
catch(InterruptedException e) {}
}
}//end bounce
public void run()
{
try
{
for (int k=0; k < 10; k++)
{
bounce ();
Thread.sleep((long)(Math.random() * 1000));
} //for
}
catch (Exception e)
{
}
}
} // end class Ball


Sign In
Create Account


Back to top









