はじめに
Swing初級から中級者向けに、4つの異なるアプリケーションを段階的に開発する方法を解説します。各アプリケーションは独立しており、難易度順に並んでいます。
各アプリケーションを完成させた後は、電卓への履歴機能、メモ帳へのシンタックスハイライト、画像ビューアへのフィルタ処理、学生管理システムへの統計グラフ表示など、さらに機能を追加することでSwingの知識や開発スキルを向上させることができます。
① 簡単な電卓アプリの作成(初級)
開発手順
基本設計
- 四則演算(+, -, *, /)ができる
- クリア(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();
解答例は別の記事にしてます。
まとめ
Swingアプリケーションを開発する際は、基本機能から拡張機能へと段階的に実装していくことが重要です。例えば、電卓ではまず四則演算を実装した後にメモリ機能を追加し、メモ帳ではテキスト編集機能を作成してから書式設定機能を拡張するといった進め方が効果的です。
デバッグでは、小さな単位で動作を確認しながら開発を進めることが大切です。また、System.out.println(“現在の値: ” + value);のようにコンソールへログを出力することで、プログラムの状態を確認しやすくなります。
コードを整理するためには、関連する機能ごとにメソッド化し、ファイル名など変更の少ない値はprivate static finalを使ってクラス定数として管理すると、保守しやすいプログラムになります。
学習を進める際は、OracleのSwingチュートリアルやGitHubのサンプルコード、Stack Overflowなどの参考リソースを活用すると理解を深められます。