Swing初級から中級者向けに、4つの異なるアプリケーションを段階的に開発する方法を解説します。各アプリケーションは独立しており、難易度順に並んでいます。
① 簡単な電卓アプリの作成(初級)
開発手順
- 基本設計
- 四則演算(+, -, *, /)ができる
- クリア(C)とイコール(=)ボタンを配置
- 入力と結果表示用のディスプレイ領域
- UIの構築
// 電卓のフレーム作成
JFrame frame = new JFrame("簡単な電卓");
frame.setSize(300, 400);
frame.setLayout(new BorderLayout());
// ディスプレイ
JTextField display = new JTextField();
display.setEditable(false);
frame.add(display, BorderLayout.NORTH);
// ボタンパネル
JPanel buttonPanel = new JPanel(new GridLayout(4, 4, 5, 5));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
- ボタン配置とイベント処理
for (String text : buttons) {
JButton button = new JButton(text);
button.addActionListener(e -> {
String cmd = e.getActionCommand();
// ここに処理を実装
});
buttonPanel.add(button);
}
- 計算ロジックの実装
- 数値入力の蓄積
- 演算子の処理
- 計算実行(=押下時)
- 完成形のヒント
// 計算ロジックの例
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
// 他の演算子も同様に
}
解答例は別の記事にしてます。
② メモ帳アプリの作成(初級~中級)
開発手順
- 基本設計
- テキスト編集領域
- ファイル操作(新規、開く、保存、終了)
- 簡単な書式設定(フォント変更)
- メインコンポーネントの配置
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
// メニューバーの作成
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("ファイル");
JMenuItem newItem = new JMenuItem("新規作成");
// 他のメニュー項目も追加
- ファイル操作の実装
newItem.addActionListener(e -> {
textArea.setText("");
currentFile = null;
});
// ファイル保存の例
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (PrintWriter writer = new PrintWriter(file)) {
writer.write(textArea.getText());
} catch (IOException ex) {
ex.printStackTrace();
}
}
- 追加機能の実装
- フォントダイアログの使用
- 検索機能(オプション)
- 完成形のヒント
// フォント変更の例
FontDialog fontDialog = new FontDialog(frame, true);
fontDialog.setVisible(true);
if (fontDialog.isApproved()) {
textArea.setFont(fontDialog.getSelectedFont());
}
解答例は別の記事にしてます。
③ 画像ビューアの作成(中級)
開発手順
- 基本設計
- 画像の読み込みと表示
- ズームイン/アウト機能
- 前後の画像への移動(ディレクトリ内)
- 画像表示コンポーネント
class ImagePanel extends JPanel {
private BufferedImage image;
private double scale = 1.0;
public void setImage(BufferedImage image) {
this.image = image;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int w = (int)(image.getWidth() * scale);
int h = (int)(image.getHeight() * scale);
g.drawImage(image, 0, 0, w, h, this);
}
}
}
- ツールバーの実装
JToolBar toolBar = new JToolBar();
JButton openButton = new JButton("開く");
JButton zoomInButton = new JButton("拡大");
JButton zoomOutButton = new JButton("縮小");
openButton.addActionListener(e -> {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage img = ImageIO.read(chooser.getSelectedFile());
imagePanel.setImage(img);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
- 追加機能の実装
- 画像の回転
- スライドショー機能(オプション)
- 完成形のヒント
// 画像回転の例
AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(90), image.getWidth()/2, image.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
image = op.filter(image, null);
解答例は別の記事にしてます。
④ 学生情報管理システム(簡易版)(中級~上級)
開発手順
- 基本設計
- 学生情報(学籍番号、氏名、成績)の管理
- 一覧表示、追加、編集、削除機能
- データの永続化(ファイル保存)
- データモデルの定義
class Student {
private String id;
private String name;
private int score;
// コンストラクタ、ゲッター、セッター
}
// テーブルモデル
class StudentTableModel extends AbstractTableModel {
private List students = new ArrayList<>();
private String[] columnNames = {"学籍番号", "氏名", "成績"};
@Override
public int getRowCount() { return students.size(); }
// 他の必須メソッド
}
- メイン画面の構成
// テーブル
JTable table = new JTable(new StudentTableModel());
JScrollPane scrollPane = new JScrollPane(table);
// ボタンパネル
JButton addButton = new JButton("追加");
JButton editButton = new JButton("編集");
JButton deleteButton = new JButton("削除");
- ダイアログの実装
// 学生追加/編集ダイアログ
class StudentDialog extends JDialog {
private JTextField idField = new JTextField(10);
private JTextField nameField = new JTextField(10);
private JSpinner scoreSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1));
public StudentDialog(Frame owner, boolean modal) {
super(owner, "学生情報", modal);
// レイアウト設定
}
public Student getStudent() {
return new Student(idField.getText(), nameField.getText(),
(Integer)scoreSpinner.getValue());
}
}
- データ永続化の実装
// 保存
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students.dat"))) {
oos.writeObject(students);
}
// 読み込み
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat"))) {
students = (List)ois.readObject();
}
- 完成形のヒント
// テーブル更新の例
((StudentTableModel)table.getModel()).addStudent(dialog.getStudent());
table.revalidate();
table.repaint();
解答例は別の記事にしてます。
学習の進め方アドバイス
- 段階的な実装
- 各アプリを「基本機能→拡張機能」の順で実装
- 電卓:四則演算→メモリ機能
- メモ帳:テキスト編集→書式設定
- デバッグのコツ
- 小さな単位で動作確認
- コンソールにログ出力
System.out.println("現在の値: " + value);
- コード整理
- 関連する機能ごとにメソッド化
- 定数はクラス定数として定義
private static final String SAVE_FILE = "students.dat";
- 参考リソース
- OracleのSwingチュートリアル
- GitHubのサンプルコード
- Stack Overflowでの質問
各アプリケーションを完成させたら、以下のような拡張に挑戦してみましょう:
- 電卓:履歴機能の追加
- メモ帳:シンタックスハイライト
- 画像ビューア:フィルタ処理
- 学生管理:統計グラフの表示
このステップバイステップのアプローチで、Swingのスキルを確実に向上させることができます!