代码部分
class BounceThread
{
public static void main(String[] args)
{
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class BounceFrame extends JFrame {//面板
public BounceFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("墙撞球");
panel = new BallPanel();
add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "增加",
event -> addBall());
add(buttonPanel, BorderLayout.SOUTH);
}
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
public void addBall()//每增加一个球就开始一个线程
{
Ball b = new Ball();
panel.add(b);
Runnable r = new BallRunnable(b, panel);
Thread t = new Thread(r);
t.start();
}
private BallPanel panel;
public static final int DEFAULT_WIDTH = 450;//宽
public static final int DEFAULT_HEIGHT = 350;//高
}
class BallRunnable implements Runnable {
public BallRunnable(Ball aBall, Component aComponent)
{
ball = aBall;
component = aComponent;
}
public void run()//
{
try
{
while(true)
{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);//影响整体球的速度
}
} catch (InterruptedException e)
{
}
}
private Ball ball;
private Component component;
public static final int DELAY = 5;
}
class Ball {//球类
Random r=new Random();
Color c=new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256),r.nextInt(256));//随机颜色
private static final int XSIZE = 15;//尺寸
private static final int YSIZE = 15;
private double x = r.nextInt(450);
private double y = r.nextInt(350);//生成球的位置
private double dx = r.nextInt(10)-5;
private double dy = r.nextInt(10)-5;//决定方向和速度
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
public void move(Rectangle2D bounds)//球的移动
{
x += dx;
y += dy;
if (x < bounds.getMinX())
{
x = bounds.getMinX();
dx = -dx;
}
if (x + XSIZE >= bounds.getMaxX())
{
x = bounds.getMaxX() - XSIZE;
dx = -dx;
}
if (y < bounds.getMinY())
{
y = bounds.getMinY();
dy = -dy;
}
if (y + YSIZE >= bounds.getMaxY())
{
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
}
}
class BallPanel extends JPanel//球的画笔
{
Random r=new Random();
private ArrayList<Ball> balls = new ArrayList<Ball>();//球集合
public void add(Ball b)
{
balls.add(b);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls)//画每一个球
{
//Color c=new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256),r.nextInt(256));
g2.setPaint(b.c);//设置画笔的颜色为小球的颜色
g2.fill(b.getShape());
}
}
}
运行截图: