
Swingアプリ開発ステップアップガイド
Swing初級から中級者向けに、4つの異なるアプリケーションを段階的に開発する方法を解説します。各アプリケーションは独立しており、難易度順に並んでいます。 ① […]
Java Swingで簡単なダイアログを表示するには、JOptionPane
クラスが便利です。確認メッセージ、入力フォーム、警告表示など、様々な種類のダイアログを数行のコードで実装できます。
import javax.swing.*;
public class MessageDialogExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// 基本メッセージダイアログ
JOptionPane.showMessageDialog(
null, // 親コンポーネント(nullで画面中央)
"処理が正常に完了しました", // メッセージ
"成功", // タイトル
JOptionPane.INFORMATION_MESSAGE // メッセージタイプ
);
// 警告メッセージ
JOptionPane.showMessageDialog(
null,
"ディスクの空き容量が少なくなっています",
"警告",
JOptionPane.WARNING_MESSAGE
);
// エラーメッセージ
JOptionPane.showMessageDialog(
null,
"ファイルが見つかりません",
"エラー",
JOptionPane.ERROR_MESSAGE
);
});
}
}
import javax.swing.*;
public class ConfirmDialogExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
int response = JOptionPane.showConfirmDialog(
null,
"本当に削除しますか?",
"確認",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE
);
if (response == JOptionPane.YES_OPTION) {
System.out.println("削除が選択されました");
} else {
System.out.println("削除がキャンセルされました");
}
});
}
}
import javax.swing.*;
public class InputDialogExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// テキスト入力ダイアログ
String name = JOptionPane.showInputDialog(
null,
"あなたの名前を入力してください:",
"ユーザー登録",
JOptionPane.PLAIN_MESSAGE
);
if (name != null && !name.isEmpty()) {
JOptionPane.showMessageDialog(
null,
"こんにちは、" + name + "さん!",
"挨拶",
JOptionPane.INFORMATION_MESSAGE
);
} else {
JOptionPane.showMessageDialog(
null,
"名前が入力されませんでした",
"エラー",
JOptionPane.ERROR_MESSAGE
);
}
});
}
}
JOptionPane
では、より複雑なダイアログも作成できます。
import javax.swing.*;
import java.awt.*;
public class CustomDialogExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// カスタムパネルの作成
JPanel panel = new JPanel(new GridLayout(2, 2, 5, 5));
JTextField usernameField = new JTextField(15);
JPasswordField passwordField = new JPasswordField(15);
panel.add(new JLabel("ユーザー名:"));
panel.add(usernameField);
panel.add(new JLabel("パスワード:"));
panel.add(passwordField);
int result = JOptionPane.showConfirmDialog(
null,
panel,
"ログイン情報を入力",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE
);
if (result == JOptionPane.OK_OPTION) {
String username = usernameField.getText();
char[] password = passwordField.getPassword();
JOptionPane.showMessageDialog(
null,
"ユーザー名: " + username + "\nパスワード長: " + password.length,
"入力情報",
JOptionPane.INFORMATION_MESSAGE
);
}
});
}
}
import javax.swing.*;
import java.awt.*;
public class CustomOptionDialog {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// カスタムアイコン
ImageIcon icon = new ImageIcon("path/to/icon.png");
// カスタムボタンオプション
Object[] options = {"保存", "破棄", "キャンセル"};
int choice = JOptionPane.showOptionDialog(
null,
"ドキュメントに変更があります。どうしますか?",
"ドキュメントの保存",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
icon,
options,
options[0] // デフォルト選択
);
switch(choice) {
case 0 -> System.out.println("保存が選択されました");
case 1 -> System.out.println("破棄が選択されました");
case 2 -> System.out.println("キャンセルが選択されました");
default -> System.out.println("ダイアログが閉じられました");
}
});
}
}
import javax.swing.*;
import java.awt.event.*;
public class FileSaveExample extends JFrame {
private JTextArea textArea;
public FileSaveExample() {
setTitle("簡易テキストエディタ");
setSize(500, 400);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // 閉じる操作をカスタマイズ
// ウィンドウ閉じる時の確認ダイアログ
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
confirmExit();
}
});
textArea = new JTextArea();
add(new JScrollPane(textArea));
JButton saveButton = new JButton("保存");
saveButton.addActionListener(e -> showSaveDialog());
JPanel buttonPanel = new JPanel();
buttonPanel.add(saveButton);
add(buttonPanel, BorderLayout.SOUTH);
}
private void confirmExit() {
int result = JOptionPane.showConfirmDialog(
this,
"変更が保存されていません。終了しますか?",
"確認",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else if (result == JOptionPane.NO_OPTION) {
dispose();
}
// CANCELの場合は何もしない
}
private void showSaveDialog() {
String[] options = {"上書き保存", "別名で保存", "キャンセル"};
int choice = JOptionPane.showOptionDialog(
this,
"保存方法を選択してください",
"保存オプション",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);
switch(choice) {
case 0 -> JOptionPane.showMessageDialog(this, "上書き保存しました");
case 1 -> {
String fileName = JOptionPane.showInputDialog(
this,
"ファイル名を入力:",
"別名で保存",
JOptionPane.PLAIN_MESSAGE
);
if (fileName != null) {
JOptionPane.showMessageDialog(this,
fileName + " として保存しました");
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new FileSaveExample().setVisible(true);
});
}
}
null
ではなくメインウィンドウを指定すると、ダイアログが適切な位置に表示されますnull
チェックを行いましょうINFORMATION_MESSAGE
、WARNING_MESSAGE
、ERROR_MESSAGE
を使い分けJOptionPane
はモーダルダイアログなので、表示中は他のウィンドウ操作がブロックされます// 国際化対応の例
String title = ResourceBundle.getBundle("Messages").getString("dialog.title");
String message = ResourceBundle.getBundle("Messages").getString("dialog.message");
JOptionPane.showMessageDialog(frame, message, title, JOptionPane.INFORMATION_MESSAGE);
JOptionPane
を活用することで、簡単にプロフェッショナルなダイアログを表示できます。複雑な要件にはJDialog
クラスを使用したカスタムダイアログの作成も検討しましょう。