StateMachine class


High-level virtual events

StateMachine is the base class for all SwingStates state machines. It can handle high-level events and time out events. The following code fires a high-level virtual event to a state machine sm:

sm.processEvent(new VirtualEvent("play"));

Any high-level event of type VirtualEvent has a key string to identify it. This key string can be used in transitions to refer it:

sm = new StateMachine() {

	public State off = new State() {
		Transition on = new Event("play", ">> on") { };
	};

	public State on = new State() {
		Transition off = new Event("stop", ">> off") { };
	};

};

Creating more advanced events can be done by deriving VirtualEvent class. For example, we can define song events that contain the name of a song:

class SongEvent extends VirtualEvent {

	String songName;

	public SongEvent(String event, String songName) {
		super(event);
		this.songName = songName;
	}

	public String getSongName() {
		return songName;
	}

}

If one fires a song event, e.g. sm.processEvent(new SongEvent("play", "mySong.mp3")), the title of the song can be retrieved in the transition as shown below:

	public State off = new State() {
		Transition on = new Event("play", ">> on") {
			public void action() {
				System.out.println("play "+((SongEvent)getEvent()).getSongName());
			}
		};
	};

Timer events

Each state machine contains a default timer that can be armed using method armTimer(int delay, boolean repeat), e.g.:

sm.armTimer(200, false);
Once this method called, a time out event will occur in 200 milliseconds. This event triggers transitions of class TimeOut. On the example below, the player is off 200 milliseconds after having received a "stop" event:
sm = new StateMachine() {

	public State off = new State() {		
		Transition on = new Event("play", ">> on") { };
	};

	public State on = new State() {
		Transition off = new Event("stop", ">> wait") {
			// Stop after a short delay of 200 ms
			public void action() {
				armTimer(200, false);
			}
		};
	};

	public State wait = new State() {		
		Transition endDelay = new TimeOut(">> off") { };
	};

};

The method armTimer has two arguments:

Although each state machine has a single default timer, it is possible to arm additional timers that are identified by a string tag. Method armTimer(String tag, int delay, boolean repeat) arms an additional timer that also trigger TimeOut transitions or more specific ones. A TaggedTimeOut transition takes a string tag in its constructor and is triggered only by timers are labeled by this tag.