package xiaoball; import java.awt.Color; import java.awt.Graphics; public class Ball { int x; int y; int speed; Color c; int d; int dir; public static final int ru = 1; public static final int rd = 2; public static final int lu = 3; public static final int ld = 4; public Ball() { dir = (int) (Math.random() * 4) + 1; x = (int) (Math.random() * 800); y = (int) (Math.random() * 600); speed = (int) (Math.random() * 10) + 5; c = new Color((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256)); d = (int) (int) (Math.random() * 40) + 10; } public void drawBall(Graphics g) { g.setColor(c); g.fillOval(x, y, d, d); } public void Change() { switch (dir) { // TODO 自动生成的方法存根 case ru: x += speed; y -= speed; if (y < 0) { dir = rd; } if (x > 800) { dir = lu; } break; case rd: x += speed; y += speed; if (x > 800) { dir = ld; } if (y > 600) { dir = ru; } break; case lu: x -= speed; y -= speed; if (x < 0) { dir = ru; } if (y < 0) { dir = ld; } break; case ld: x -= speed; y += speed; if (x < 0) { dir = rd; } if (y > 600) { dir = lu; } break; default: break; } } } package xiaoball; import javax.swing.JFrame; public class BallFrame { public static void main(String[] args) { BallPanel p=new BallPanel(); JFrame f=new JFrame(); f.add(p); f.setSize(800, 600); f.setDefaultCloseOperation(3); f.setLocationRelativeTo(null); f.setVisible(true); f.addMouseListener(p); p.move(); } } package xiaoball; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JPanel; @SuppressWarnings("serial") public class BallPanel extends JPanel implements MouseListener { Ball[] bs = new Ball[200]; public BallPanel() { for (int i = 0; i < bs.length; i++) { bs[i] = new Ball(); } } @Override public void paint(Graphics g) { // TODO 自动生成的方法存根 super.paint(g); for (int i = 0; i < bs.length; i++) { bs[i].drawBall(g); } } public void move() { new Thread() { public void run() { while (true) { for (int i = 0; i < bs.length; i++) { bs[i].Change(); } repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }.start(); } @Override public void mouseClicked(MouseEvent e) { // TODO 自动生成的方法存根 System.exit(0); } @Override public void mousePressed(MouseEvent e) { // TODO 自动生成的方法存根 } @Override public void mouseReleased(MouseEvent e) { // TODO 自动生成的方法存根 } @Override public void mouseEntered(MouseEvent e) { // TODO 自动生成的方法存根 } @Override public void mouseExited(MouseEvent e) { // TODO 自动生成的方法存根 } }