/* * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM) * Published By SunSoft Press/Prentice-Hall * Copyright (C) 1996 Sun Microsystems Inc. * All Rights Reserved. ISBN 0-13-565755-5 * * Permission to use, copy, modify, and distribute this * software and its documentation for NON-COMMERCIAL purposes * and without fee is hereby granted provided that this * copyright notice appears in all copies. * * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. */ /** * @version 1.00 07 Feb 1996 * @author Cay Horstmann */ import java.awt.*; public class BounceThread extends Frame { public BounceThread() { setTitle("BounceThread"); canvas = new Canvas(); add("Center", canvas); Panel p = new Panel(); p.add(new Button("Start")); p.add(new Button("Close")); add("South", p); } public boolean handleEvent(Event evt) { if (evt.id == Event.WINDOW_DESTROY) System.exit(0); return super.handleEvent(evt); } public boolean action(Event evt, Object arg) { if (arg.equals("Start")) { Ball b = new Ball(canvas); b.start(); } else if (arg.equals("Close")) System.exit(0); else return super.action(evt, arg); return true; } public static void main(String[] args) { Frame f = new BounceThread(); f.resize(300, 200); f.show(); } private Canvas canvas; } class Ball extends Thread { public Ball(Canvas c) { box = c; } public void draw() { Graphics g = box.getGraphics(); g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); } public void move() { Graphics g = box.getGraphics(); g.setXORMode(box.getBackground()); g.fillOval(x, y, XSIZE, YSIZE); x += dx; y += dy; Dimension d = box.size(); 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(5); } catch(InterruptedException e) {} } } 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; }