import java.awt.*;
import java.lang.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class BallGame extends JFrame implements ActionListener
{
JButton jbtStart = new JButton("Start");
JButton jbtStop = new JButton("Stop");
MainPanel mp = new MainPanel();
public BallGame()
{
this.getContentPane().add(mp,BorderLayout.CENTER);
mp.setBackground(Color.white);
JPanel p=new JPanel();
p.add(jbtStart);
p.add(jbtStop);
this.getContentPane().add(p,BorderLayout.SOUTH);
jbtStart.addActionListener(this);
jbtStop.addActionListener(this);
}
public static void main(String[] args)
{
BallGame bt = new BallGame();
bt.setSize(300,300);
bt.setVisible(true);
bt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==jbtStart)
{
BallThread b=new BallThread(mp);
mp.balls.addElement(b);
b.start();
}
else
{
System.exit(0);
}
}
}
class MainPanel extends Panel
{
public Vector balls=new Vector();
public void paint(Graphics g)
{
for(int i=0;i<balls.size();i++)
{
BallThread ball = (BallThread)balls.elementAt(i);
ball.draw();
}
}
}
class BallThread extends Thread
{
MainPanel mainPanel;
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 BallThread(MainPanel b)
{
mainPanel=b;
}
public void draw()
{
Graphics g=mainPanel.getGraphics();
g.fillOval(x,y,XSIZE,YSIZE);
g.dispose();
}
public void move()
{
x+=dx;
y+=dy;
Dimension d=mainPanel.getSize();
if(x<0){x=0;dx=-dx;}
if(y<0){y=0;dy=-dy;}
if(x+XSIZE>=d.width ) {x=d.width -XSIZE;dx=-dx;}
if(y+YSIZE>=d.height ) {y=d.height -YSIZE;dy=-dy;}
mainPanel.repaint();
}
public void run()
{
try
{
draw();
while(true)
{
move();
sleep(30);
}
}catch(Exception e){ }
}
}