GT Computing Home Page

GT Computing Home Page

The Digit Actor

The controlling script for the clock digits looks like this:

//	Digit.java

import java.awt.*;
import java.util.*;
import linguist.quickshow.*;

public class Digit extends Actor
{
	Digit(Stage stage,int id)
	{
		super(stage,"Digit",id);
	}

	public void run()
	{
		int left=0;
		switch (getID())
		{
			case 0: left=18; break;
			case 1: left=60; break;
			case 2: left=130; break;
			case 3: left=172; break;
		}
		loadImageSequence("gif/D2-","0","9",".gif",left,20);
		setCurrentView(0);
		show();
		setReady();
		new DigitModifier(this);
		int min=-1;
		addMouseListener(new ActorAdapter()
		{
			public void mousePressed(Actor a)
			{
				Color c=Color.black;
				switch (getID())
				{
					case 0: c=Color.red; break;
					case 1: c=Color.green; break;
					case 2: c=Color.blue; break;
					case 3: c=Color.gray; break;
				}
				postMessage("Background","color",c);
			}
		});
		while (true)
		{
			pause(1000);
			Date d=new Date();
			int m=d.getMinutes();
			if (m!=min)
			{
				int view=0;
				switch (getID())
				{
					case 0: view=d.getHours()/10; break;
					case 1: view=d.getHours()%10; break;
					case 2: view=d.getMinutes()/10; break;
					case 3: view=d.getMinutes()%10; break;
				}
				setCurrentView(view);
				min=m;
			}
		}
	}
}

This class requires an ID for its constructor, which identifies which digit is being referred to. Two switch() statements then provide all the code that differs from one digit to another, viz. the position of the digit and the source of its data.

When a digit is clicked the class posts a message to the Background Actor telling it to change colour. This illustrates a key feature of QuickShow; there's usually no need to expose the methods of your Actor subclasses. Instead, send them messages and let them call their own methods. You'll find this will avoid a lot of unnecessary casting. The only exception is where performance is an issue; processing text messages is more time-consuming.

The methods postMessage() and sendMessage() do much the same thing, but the former causes the message to be sent to the Actor in a new thread, allowing processing to continue without waiting for a reply. In contrast, sendMessage() waits for the message to be received and acted upon. It also returns an Object containing any data the called Actor might have supplied. Use postMessage() wherever possible as it makes better use of threads, but don't make any assumptions about the order in which messages are processed. If you need to be sure of the order, use sendMessage().

Note that the code that causes the digits to shrink and grow is nowhere to be seen. In fact, it's handled by the DigitModifer object, to which we pass our Actor so it knows which digit to mess about with.