advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

ShapesApplet


import java.awt.*;
import java.lang.Math;
import java.util.Random;

/**
  A simple applet to illustrate multithreaded programming.
  It consists of shapes, each running in its own thread that
  ebb and flow at different rates.

  @Author: Suresh Srinivasan (suresh@thomtech.com)
  @Date: Oct 1995
  @Version: 0.1
 */

public class ShapesApplet extends java.applet.Applet {
    public int W = 400;
    public int H = 100;
    public int N = 15;
    public final int minSize = 10;
    public final int maxSize = 50;
    public final int minNaptime = 1;
    public final int maxNaptime = 500;
    public final Color colors[] = {
	Color.red,
	Color.pink,
	Color.orange,
	Color.yellow,
	Color.green,
	Color.magenta,
	Color.blue,
	Color.cyan,
	Color.white,
	Color.gray,
	Color.lightGray,
	Color.darkGray
    };
    public final Color bg = Color.black;
    boolean threadSuspended = false;
    Image im;
    Graphics offscreen;
    Random rand;
    Shape shapes[] = new Shape[N];

    public void init() {
	resize(W, H);
	rand = new Random((long)System.currentTimeMillis());
	try {
	    im = createImage(W, H);
	    offscreen = im.getGraphics();
	} catch (Exception e) {
	    offscreen = null;
	}
    }

/*
  Create each shape with some random parameters and start its thread
  */
    public void start() {
	for (int i=0; i<N; i++) {
	    if (shapes[i] == null) {
		shapes[i] = new Shape(this,
		    (int)((double)W*rand.nextDouble()),
		    (int)((double)H*rand.nextDouble()),
		    minSize + (int)((double)(maxSize-minSize)*rand.nextDouble()),
		    minNaptime + (int)((double)(maxNaptime-minNaptime)*rand.nextDouble()),
		    colors[(int)((double)colors.length*rand.nextDouble())],
		    bg);
		shapes[i].start();
	    }
	}
	repaint();
    }

/* when applet is stopped, stop individual threads */
    public void stop() {
	for (int i=0; i<N; i++) {
	    shapes[i].stop();
	}
    }

/* override the update method to reduce flashing */
    public void update(Graphics g) {
	paint(g);
    }

/* we are using double buffering to reduce flashing */
    public void paint(Graphics g) {
	if (offscreen != null) {
	    paintApplet(offscreen);
	    g.drawImage(im, 0, 0, this);
	} else {
	    paintApplet(g);
	}
    }

/* call each shape's paint method */
    public void paintApplet(Graphics g) {
	boolean changed = false;

	g.setColor(bg);
	g.fillRect(0, 0, W, H);
	for (int i=0; i<N; i++) {
	    shapes[i].paint(g);
	}
    }

/* on mouse activity, suspend (or resume) each shape's thread */
    public boolean mouseDown(Event e, int x, int y) {
	if (threadSuspended) {
	    for (int i=0; i<N; i++)
		shapes[i].thread.resume();
	} else {
	    for (int i=0; i<N; i++)
		shapes[i].thread.suspend();
	}
	threadSuspended = !threadSuspended;
	return(true);
    }

}

/**
  Implements a Shape.  Each shape will call its applet's paint method
  asynchronously when it is time for growth or decay.
  */
class Shape implements Runnable {
    static int threadNum = 1;
    private Color color = null;
    private Color bg = Color.black;
    private int naptime = 500;
    private int size = 50;
    private int growthFactor = 1;
    private int ox = 0;		/* location within applet's frame of reference */
    private int oy = 0;
    private Graphics graphics;
    private int current;
    private int previous;
    private boolean growing = false;

    public Thread thread = null;
    public boolean changed = true;

    ShapesApplet applet;

    public Shape(ShapesApplet applet, int x, int y, int s, int n, Color c, Color bg) {
	this.applet = applet;
	ox = x;
	oy = y;
	size = s;
	naptime = n;
	color = c;
	if (color == null) {
	    color = Color.black;
	}
	current = previous = s;
    }

/* the thread's run method */
    public void run() {
	thread.setPriority(Thread.MIN_PRIORITY+1);
	while (thread != null) {
	    changed = true;
	    previous = current;
	    if (growing) {
		current += growthFactor;
	    } else {
		current -= growthFactor;
	    }
	    if (current == size || current == 0) {
		growing = !growing;
	    }
	    try { thread.sleep(naptime); } catch (InterruptedException e) {};
	    applet.repaint();
	}
	thread = null;
    }

/* start the thread */
    public void start() {
	if (thread == null) {
	    thread = new Thread(this, Integer.toString(threadNum++));
	    thread.start();
	}
    }

    public void stop() {
	thread = null;
    }

/* unpaint last position and paint the new one */
    public void paint(Graphics g) {
	int prevHalf = (int)(previous/2);
	int curHalf = (int)(current/2);

	g.setColor(bg);
	g.fillRect(ox-prevHalf, oy-prevHalf, previous, previous);
//	g.fillOval(ox-prevHalf, oy-prevHalf, previous, previous);

	g.setColor(color);
	g.fillRect(ox-curHalf, oy-curHalf, current, current);
//	g.fillOval(ox-curHalf, oy-curHalf, current, current);
    }
}


Back to the ShapesApplet applet page

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs