GT Computing Home Page

GT Computing Home Page

The Background Actor

Here's a listing of this class:

//	Background.java

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

public class Background extends Actor
{
	Background(Stage stage)
	{
		super(stage,"Background");
	}

	public void run()
	{
		createImage(240,100);
		setColor(Color.gray);
		setReady();
	}

	private void setColor(Color c)
	{
		Graphics g=getImage().getGraphics();
		g.setColor(c);
		g.fillRect(0,0,240,100);
		g.dispose();
		show();
	}

	////////////////////////////////////////////////////////////
	//	Message handler.

	public Object handleMessage(String command,Object data)
	{
		if (command.equals("color"))
		{
			setColor((Color)data);
			return "OK";
		}
		return null;
	}
}

This Background class doesn't load an image file; instead it creates a drawable image then fills it with a standard colour by requesting a Graphics context from its Image. This is one way of doing custom graphics on an Actor. The other is to override the paint() method, but this way is sometimes simpler and requires no knowledge of how paint() works.

The class also allows others to change its background colour by means of a QuickShow message. But even though the Background is behind all the other Actors, the Stage ensures they'll all be redrawn correctly.