package main;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
public class Ball {
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1;
public Ball()
{
x = Math.random() * (450 - XSIZE);
y = Math.random() * (350 - YSIZE);
}
public void move(Rectangle2D bounds)
{
x += dx;
y += dy;
if (x < bounds.getMinX())
{
x = bounds.getMinX();
dx = -dx;
}
if (y < bounds.getMinY())
{
y = bounds.getMinY();
dy = -dy;
}
if (x + XSIZE > bounds.getMaxX())
{
x = bounds.getMaxX() - XSIZE;
dx = -dx;
}
if (y + YSIZE > bounds.getMaxY())
{
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
}
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
}
package main;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.awt.Dimension;
import javax.swing.JPanel;
public class BallPanel extends JPanel
{
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350;
//Ball ball;
ArrayList<Ball> BallList;
public BallPanel()
{
BallList = new ArrayList<Ball>();
}
public Ball add()
{
Ball tmp = new Ball();
BallList.add(tmp);
return tmp;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Ball ball : BallList)
{
g2.fill(ball.getShape());
}
//ball.move(getBounds());
}
public Dimension getPreferredSize()
{
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
class BallThread extends Thread
{
BallPanel panel;
Ball ball;
public BallThread(Ball ball, BallPanel panel)
{
this.ball = ball;
this.panel = panel;
}
public void run()
{
while (true)
{
ball.move(panel.getBounds());
try
{
Thread.sleep(1);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
panel.repaint();
}
}
}
package main;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
public class BallFrame extends JFrame
{
BallPanel panel;
public BallFrame()
{
panel = new BallPanel();
add(panel, BorderLayout.CENTER);
JButton button1 = new JButton("start");
JPanel ButtonPanel = new JPanel();
button1.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
BallThread thread = new BallThread(panel.add(), panel);
thread.start();
}
}
);
ButtonPanel.add(button1);
add(ButtonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run() {
// TODO Auto-generated method stub
BallFrame frame = new BallFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
);
}
}