Nullレイアウト処理(NullLayout)

/*
 * nullレイアウト処理のクラス
 * 
 * nullレイアウトでは、自分の表示したい位置を
 * ピクセルで指定することができます。
 * 一番自由度が利くレイアウトですが、その分、
 * 配置がとても難しいです。
 * 
 * 例は、ボタン処理とまったく同じプログラムを使用。
 * 
 * ※setBoundsで指定した場所で表示することが可能。
 */
package layout;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class NullLayout implements ActionListener {
  	private JFrame frame;
	private JButton button1;
	private MyPanel panel;

	public NullLayout() {
		frame = new JFrame();
			
		button1 = new JButton("ボタン1");
		panel = new MyPanel();

		frame.setTitle("ここにタイトル");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setBounds(300, 400, 200, 200);

		// コンポーネントに指定された位置で表示を行う。
		frame.getContentPane().setLayout(null);
		frame.getContentPane().add(panel, null);

		// ボタンの表示位置を設定
		button1.setBounds(50, 110, 100, 40);
		button1.addActionListener(this);
		frame.getContentPane().add(button1);

		frame.setVisible(true);
	}

	public static void main(String args[]) {
		new NullLayout();
	}

	public void actionPerformed(ActionEvent ae) {
		if( ae.getActionCommand() == "ボタン1" ) {
			System.out.println("ボタンをクリックしました");
			panel.changeColor();
			panel.repaint();
		}
	}
}

class MyPanel extends JPanel {
	private Color col = Color.red;

	public MyPanel() {
		// コンポーネントの表示位置を設定。
		// setBoundsの引数は、
		// 始点x座標, 始点y座標, width, height
		setBounds(0, 0, 100, 100);
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.setColor(col);
		g.fillRect(0, 0, 100, 100);
	}

	// ボタンが押された時、色を変える処理
	public void changeColor() {
		if( col == Color.red ) {
			col = Color.blue;
		}else{
			col = Color.red;
	}
}