/* * Bouncing balls - each ball is a different thread with a different * time to sleep. */ import java.awt.*; import java.awt.event.*; public class BounceSynch extends Frame implements ActionListener { private Canvas canvas; public BounceSynch() { setLayout(new BorderLayout()); setTitle("BounceSynch"); canvas = new Canvas(); add(canvas, BorderLayout.CENTER); Panel p = new Panel(); Button b1 = new Button("Start"); b1.addActionListener(this); p.add(b1); Button b2 = new Button("Close"); b2.addActionListener(this); p.add(b2); add(p, BorderLayout.SOUTH); } public void actionPerformed(ActionEvent evt) { if (evt.getActionCommand().equals("Start")) { BallSynch b = new BallSynch(canvas); b.start(); } else if (evt.getActionCommand().equals("Close")) System.exit(0); } public static void main(String[] args) { Frame f = new BounceSynch(); f.setSize(400, 300); f.setVisible(true); } } class BallSynch extends Thread { private Canvas box; private static final int XSIZE = 10; private static final int YSIZE = 10; private int x = 0; private int y = 0; private int dx = 2; private int dy = 2; private int sleeptime; public BallSynch(Canvas c) { box = c; sleeptime = ((int)(Math.random() * 40)) + 4; } public synchronized void draw() { Graphics g = box.getGraphics(); g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); } public synchronized void move() { Graphics g = box.getGraphics(); g.setXORMode(box.getBackground()); g.fillOval(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.fillOval(x, y, XSIZE, YSIZE); g.dispose(); } public void run() { draw(); for (int i = 1; i <= 1000; i++) { move(); try { Thread.sleep(sleeptime); } catch(InterruptedException e) {} } } }