Canvas クラスの例

import java.awt.*;
import java.awt.event.*;

public class Test {
	public static void main (String[] args)
	{
		Win win = new Win("Test Window", "Test Data");
	}
}

/*******************/
/* クラスWinの定義 */
/*******************/
class Win extends Frame implements ActionListener {

	Button bt;
	TestCanvas tc;

	/******************/
	/* コンストラクタ */
	/******************/
	Win (String name, String data)
	{
					// Frameクラスのコンストラクタ(Windowのタイトルを引き渡す)
		super(name);
					// レイアウトの変更(行,列,水平ギャップ,垂直ギャップ)
		setLayout(new GridLayout(2, 1, 5, 10));
					// 上のパネル
		Font f = new Font("MS 明朝", Font.PLAIN, 30);
						// パネルの追加
		Panel pn1 = new Panel();
		add(pn1);
						// ボタンの追加
		bt = new Button("スタート");
		bt.setFont(f);
		bt.addActionListener(this);
		pn1.add(bt);
					// 下のパネル
						// パネルの追加
		Panel pn2 = new Panel();
		add(pn2);
						// Canvasの追加
		tc = new TestCanvas();
		tc.setSize(270, 150);
		tc.setBackground(Color.cyan);
		pn2.add(tc);
					// Windowの大きさ
		setSize(300, 350);
					// ウィンドウを表示
		setVisible(true);
					// イベントアダプタ
		addWindowListener(new WinEnd());
	}

	/******************************/
	/* 上,左,下,右の余白の設定 */
	/******************************/
	public Insets getInsets()
	{
		return new Insets(35, 10, 10, 10);
	}

	/******************************/
	/* ボタンが押されたときの処理 */
	/******************************/
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == bt) {
			Point p = tc.getLocation();
			p.x += 10;
			tc.setLocation(p.x, p.y);
		}
	}

	/************/
	/* 終了処理 */
	/************/
	class WinEnd extends WindowAdapter
	{
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}
	}
}

class TestCanvas extends Canvas {
	public void paint(Graphics g)
	{
		g.setColor(Color.yellow);
		g.fillRect(10, 10, 50, 50);
	}
}