GUIアプリの起動ロジッククラス

ちょっとしたGUIアプリを作成する際にmainメソッドで毎回似たような処理を行うのですが、毎回似たような処理を書くのもなんなのでクラスにまとめてみました。

import java.awt.Dimension;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 * GUIアプリの起動ロジッククラス
 */
public class Main {
	
	/**
	 * コンストラクタ
	 * <p>
	 * 生成させないために存在します
	 */
	private Main() {
	}
	
	/**
	 * 引数で指定されたクラスをもつフレームを表示します
	 * <p>
	 * clazzに指定するクラスがJComponentのサブクラスでない場合、例外を発生します
	 * 
	 * @param clazz フレームで表示を行うJComponentのサブクラス
	 * @param title フレームのタイトル
	 */
	public static void main(final Class clazz, final String title) {
		if (clazz == null) {
			throw new NullPointerException();
		}
		if (! JComponent.class.isAssignableFrom(clazz)) {
			throw new IllegalArgumentException();
		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				initSystemLookAndFeel();
				try {
					createAndShowGUI((JComponent)clazz.newInstance(), title);
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 引数で指定されたコンポーネントをもつフレームを表示します
	 * 
	 * @param component コンポーネント
	 * @param title フレームのタイトル
	 */
	public static void createAndShowGUI(final JComponent component, final String title) {
		JFrame frame = new JFrame(title);
		frame.getContentPane().add(component);
		frame.pack();
		
		Dimension size = frame.getSize();
		Dimension screenSize = frame.getToolkit().getScreenSize();
		
		frame.setLocation((screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
	
	/**
	 * システムのルックアンドフィールに設定します
	 */
	public static void initSystemLookAndFeel() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
	}
}

このように使用します。

import javax.swing.JPanel;

public class SamplePanel extends JPanel {

	public static void main(String[] args) {
		Main.main(SamplePanel.class, "タイトル");
	}
}