Swing
Java標準のGUIツールキット。軽量コンポーネントアーキテクチャにより豊富なUI部品を提供。Look & Feelによる外観カスタマイズが可能で、成熟したAPIと豊富なドキュメントが特徴。レガシーアプリケーションで広く使用。
GitHub概要
openjdk/jdk
JDK main-line development https://openjdk.org/projects/jdk
スター21,352
ウォッチ355
フォーク6,084
作成日:2018年9月17日
言語:Java
ライセンス:GNU General Public License v2.0
トピックス
javajvmopenjdk
スター履歴
データ取得日時: 2025/7/18 01:39
フレームワーク
Swing
概要
SwingはJavaの標準GUI(グラフィカルユーザーインターフェース)ツールキットで、Java SE(Standard Edition)に標準搭載されている、デスクトップアプリケーション開発のためのフレームワークです。1997年に導入され、長年にわたりJavaによるデスクトップアプリケーション開発の中核を担ってきました。
詳細
2025年現在、SwingはJava 21 LTSを含む最新のJavaバージョンでサポートされており、エンタープライズ環境において重要な役割を果たし続けています。SwingはAWT(Abstract Window Toolkit)をベースに構築されたリッチなUIコンポーネントライブラリです。
Swingの主要な特徴:
- 100% Pure Java: プラットフォームに依存しない純粋なJava実装
- 豊富なコンポーネント: JButton、JLabel、JTable、JTree、JList等の多様なUI部品
- プラガブルLook & Feel: Metal、Nimbus、システム標準など複数の外観テーマ
- MVC アーキテクチャ: Model-View-Controller設計パターンの採用
- イベント駆動モデル: ActionListener、MouseListener等の包括的なイベント処理
- レイアウトマネージャー: BorderLayout、GridLayout、FlowLayout等の柔軟なレイアウト
- カスタマイズ性: 独自コンポーネントやカスタムレンダラーの作成が可能
エンタープライズ開発において、Swingは以下の分野で活用されています:
- 業務管理システム(ERP、CRM)
- 開発ツール(IDE、データベース管理ツール)
- 科学技術計算アプリケーション
- 金融システムのフロントエンド
- 組み込みシステムのGUI
一方で、モダンなUI/UXトレンドへの対応、Web技術の普及、JavaFXの推進により、新規プロジェクトでの採用は減少していますが、既存システムの保守・拡張では依然として重要な技術です。
メリット・デメリット
メリット
- 標準搭載: Java SEに標準で含まれており追加インストール・ライセンス不要
- 安定性: 25年以上の使用実績により極めて安定した動作保証
- プラットフォーム独立: "Write Once, Run Anywhere"の完全な実現
- 豊富なコンポーネント: 100以上の標準UIコンポーネントを提供
- エンタープライズ実績: 大企業・金融機関での長期運用実績
- 学習リソース: 膨大な数の書籍、チュートリアル、サンプルコード
- カスタマイズ性: Look & Feel、カスタムコンポーネントの高度なカスタマイズ
- デバッグ環境: 優れたIDE支援とJavaデバッギング機能
デメリット
- 古典的なデザイン: モダンなフラットデザイン・マテリアルデザインへの対応困難
- パフォーマンス: ネイティブアプリケーションと比較した動作の重さ
- 高DPI対応: 4K・高解像度ディスプレイでの表示問題
- 開発効率: 現代的なUIフレームワークと比較した冗長なコード記述
- 優先度低下: Oracle・OpenJDKコミュニティでの新機能開発の停滞
- 人材市場: 若手開発者への学習・採用の敬遠傾向
- モバイル非対応: スマートフォン・タブレット等のモバイルデバイス非対応
主要リンク
- Oracle Swing Tutorial
- Java 21 Swing API Documentation
- OpenJDK Swing Project
- Java デスクトップアプリケーション開発ガイド
- Swing Design Guidelines
- Oracle Java SE Downloads
書き方の例
基本的なSwingアプリケーション
// HelloWorldSwing.java - 基本的なSwingアプリケーション
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class HelloWorldSwing extends JFrame {
private JLabel statusLabel;
private int clickCount = 0;
public HelloWorldSwing() {
initializeGUI();
}
private void initializeGUI() {
// フレーム基本設定
setTitle("Hello World - Swing Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// ヘッダーパネル
JPanel headerPanel = new JPanel();
headerPanel.setBackground(new Color(70, 130, 180));
headerPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JLabel titleLabel = new JLabel("Hello, Swing World!", SwingConstants.CENTER);
titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
titleLabel.setForeground(Color.WHITE);
headerPanel.add(titleLabel);
// メインコンテンツパネル
JPanel mainPanel = new JPanel(new GridLayout(3, 1, 10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// システム情報表示
JPanel infoPanel = new JPanel(new GridLayout(3, 2, 5, 5));
infoPanel.setBorder(BorderFactory.createTitledBorder("システム情報"));
infoPanel.add(new JLabel("Java バージョン:"));
infoPanel.add(new JLabel(System.getProperty("java.version")));
infoPanel.add(new JLabel("OS:"));
infoPanel.add(new JLabel(System.getProperty("os.name")));
infoPanel.add(new JLabel("Look & Feel:"));
infoPanel.add(new JLabel(UIManager.getLookAndFeel().getName()));
// ボタンパネル
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.setBorder(BorderFactory.createTitledBorder("操作"));
JButton helloButton = new JButton("挨拶する");
helloButton.setPreferredSize(new Dimension(120, 30));
helloButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
JOptionPane.showMessageDialog(
HelloWorldSwing.this,
"こんにちは!これは " + clickCount + " 回目のクリックです。",
"挨拶",
JOptionPane.INFORMATION_MESSAGE
);
updateStatus("挨拶ボタンがクリックされました(" + clickCount + "回目)");
}
});
JButton exitButton = new JButton("終了");
exitButton.setPreferredSize(new Dimension(120, 30));
exitButton.addActionListener(e -> {
int result = JOptionPane.showConfirmDialog(
this,
"アプリケーションを終了しますか?",
"確認",
JOptionPane.YES_NO_OPTION
);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
}
});
buttonPanel.add(helloButton);
buttonPanel.add(exitButton);
// ステータスパネル
statusLabel = new JLabel("準備完了");
statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
// レイアウト配置
mainPanel.add(infoPanel);
mainPanel.add(buttonPanel);
add(headerPanel, BorderLayout.NORTH);
add(mainPanel, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
// ウィンドウサイズと位置
setSize(500, 400);
setLocationRelativeTo(null);
setResizable(true);
// 初期状態の設定
updateStatus("アプリケーションが開始されました");
}
private void updateStatus(String message) {
statusLabel.setText(message);
// 3秒後にデフォルトメッセージに戻す
Timer timer = new Timer(3000, e -> statusLabel.setText("準備完了"));
timer.setRepeats(false);
timer.start();
}
public static void main(String[] args) {
// システムのLook & Feelを設定
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
// EDT(Event Dispatch Thread)で実行
SwingUtilities.invokeLater(() -> {
new HelloWorldSwing().setVisible(true);
});
}
}
高度なレイアウト管理とMVCパターン
// DataManagementApp.java - MVCパターンとレイアウト管理の実装
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
public class DataManagementApp extends JFrame {
private PersonTableModel tableModel;
private JTable table;
private JTextField nameField, ageField, departmentField;
private JLabel statusLabel;
public DataManagementApp() {
initializeGUI();
setupData();
}
private void initializeGUI() {
setTitle("データ管理アプリケーション - Swing MVC Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// メニューバーの作成
createMenuBar();
// メインパネルの作成
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 上部:入力フォーム
JPanel inputPanel = createInputPanel();
// 中央:データテーブル
JPanel tablePanel = createTablePanel();
// 下部:ステータスバー
statusLabel = new JLabel("準備完了");
statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(tablePanel, BorderLayout.CENTER);
add(mainPanel, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
setSize(800, 600);
setLocationRelativeTo(null);
}
private void createMenuBar() {
JMenuBar menuBar = new JMenuBar();
// ファイルメニュー
JMenu fileMenu = new JMenu("ファイル");
fileMenu.add(createMenuItem("新規", e -> clearForm()));
fileMenu.add(createMenuItem("データエクスポート", e -> exportData()));
fileMenu.addSeparator();
fileMenu.add(createMenuItem("終了", e -> System.exit(0)));
// 編集メニュー
JMenu editMenu = new JMenu("編集");
editMenu.add(createMenuItem("全選択", e -> table.selectAll()));
editMenu.add(createMenuItem("選択解除", e -> table.clearSelection()));
// 表示メニュー
JMenu viewMenu = new JMenu("表示");
JCheckBoxMenuItem showGridMenuItem = new JCheckBoxMenuItem("グリッド表示", true);
showGridMenuItem.addActionListener(e -> table.setShowGrid(showGridMenuItem.isSelected()));
viewMenu.add(showGridMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);
setJMenuBar(menuBar);
}
private JMenuItem createMenuItem(String text, java.awt.event.ActionListener listener) {
JMenuItem item = new JMenuItem(text);
item.addActionListener(listener);
return item;
}
private JPanel createInputPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder("人員情報入力"));
// 入力フィールドパネル
JPanel fieldsPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
// 名前フィールド
gbc.gridx = 0; gbc.gridy = 0;
fieldsPanel.add(new JLabel("名前:"), gbc);
gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL;
nameField = new JTextField(15);
fieldsPanel.add(nameField, gbc);
// 年齢フィールド
gbc.gridx = 2; gbc.fill = GridBagConstraints.NONE;
fieldsPanel.add(new JLabel("年齢:"), gbc);
gbc.gridx = 3; gbc.fill = GridBagConstraints.HORIZONTAL;
ageField = new JTextField(5);
fieldsPanel.add(ageField, gbc);
// 部署フィールド
gbc.gridx = 4; gbc.fill = GridBagConstraints.NONE;
fieldsPanel.add(new JLabel("部署:"), gbc);
gbc.gridx = 5; gbc.fill = GridBagConstraints.HORIZONTAL;
departmentField = new JTextField(10);
fieldsPanel.add(departmentField, gbc);
// ボタンパネル
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addButton = new JButton("追加");
addButton.addActionListener(this::addPerson);
JButton updateButton = new JButton("更新");
updateButton.addActionListener(this::updatePerson);
JButton deleteButton = new JButton("削除");
deleteButton.addActionListener(this::deletePerson);
JButton clearButton = new JButton("クリア");
clearButton.addActionListener(e -> clearForm());
buttonPanel.add(addButton);
buttonPanel.add(updateButton);
buttonPanel.add(deleteButton);
buttonPanel.add(clearButton);
panel.add(fieldsPanel, BorderLayout.CENTER);
panel.add(buttonPanel, BorderLayout.SOUTH);
return panel;
}
private JPanel createTablePanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder("人員データ"));
// テーブルモデルの作成
tableModel = new PersonTableModel();
table = new JTable(tableModel);
// テーブルの設定
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
table.setRowHeight(25);
// セルレンダラーの設定(年齢列を右寄せ)
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
table.getColumnModel().getColumn(1).setCellRenderer(rightRenderer); // 年齢列
// 列幅の調整
table.getColumnModel().getColumn(0).setPreferredWidth(150); // 名前
table.getColumnModel().getColumn(1).setPreferredWidth(60); // 年齢
table.getColumnModel().getColumn(2).setPreferredWidth(120); // 部署
// テーブル選択イベント
table.getSelectionModel().addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
int selectedRow = table.getSelectedRow();
if (selectedRow >= 0) {
Person person = tableModel.getPersonAt(selectedRow);
nameField.setText(person.getName());
ageField.setText(String.valueOf(person.getAge()));
departmentField.setText(person.getDepartment());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void addPerson(ActionEvent e) {
try {
String name = nameField.getText().trim();
String ageText = ageField.getText().trim();
String department = departmentField.getText().trim();
if (name.isEmpty() || ageText.isEmpty() || department.isEmpty()) {
showError("すべてのフィールドを入力してください。");
return;
}
int age = Integer.parseInt(ageText);
if (age < 0 || age > 150) {
showError("年齢は0から150の間で入力してください。");
return;
}
Person person = new Person(name, age, department);
tableModel.addPerson(person);
clearForm();
updateStatus("新しい人員を追加しました: " + name);
} catch (NumberFormatException ex) {
showError("年齢は数値で入力してください。");
}
}
private void updatePerson(ActionEvent e) {
int selectedRow = table.getSelectedRow();
if (selectedRow < 0) {
showError("更新する行を選択してください。");
return;
}
try {
String name = nameField.getText().trim();
String ageText = ageField.getText().trim();
String department = departmentField.getText().trim();
if (name.isEmpty() || ageText.isEmpty() || department.isEmpty()) {
showError("すべてのフィールドを入力してください。");
return;
}
int age = Integer.parseInt(ageText);
Person person = new Person(name, age, department);
tableModel.updatePerson(selectedRow, person);
clearForm();
updateStatus("人員情報を更新しました: " + name);
} catch (NumberFormatException ex) {
showError("年齢は数値で入力してください。");
}
}
private void deletePerson(ActionEvent e) {
int selectedRow = table.getSelectedRow();
if (selectedRow < 0) {
showError("削除する行を選択してください。");
return;
}
Person person = tableModel.getPersonAt(selectedRow);
int result = JOptionPane.showConfirmDialog(
this,
"「" + person.getName() + "」を削除しますか?",
"削除確認",
JOptionPane.YES_NO_OPTION
);
if (result == JOptionPane.YES_OPTION) {
tableModel.removePerson(selectedRow);
clearForm();
updateStatus("人員を削除しました: " + person.getName());
}
}
private void clearForm() {
nameField.setText("");
ageField.setText("");
departmentField.setText("");
table.clearSelection();
}
private void exportData() {
StringBuilder sb = new StringBuilder();
sb.append("名前,年齢,部署\n");
for (Person person : tableModel.getAllPersons()) {
sb.append(person.getName()).append(",")
.append(person.getAge()).append(",")
.append(person.getDepartment()).append("\n");
}
JTextArea textArea = new JTextArea(sb.toString());
textArea.setEditable(false);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500, 300));
JOptionPane.showMessageDialog(this, scrollPane, "エクスポートデータ", JOptionPane.INFORMATION_MESSAGE);
}
private void setupData() {
// サンプルデータの追加
tableModel.addPerson(new Person("田中太郎", 30, "開発部"));
tableModel.addPerson(new Person("佐藤花子", 28, "営業部"));
tableModel.addPerson(new Person("鈴木一郎", 35, "企画部"));
tableModel.addPerson(new Person("高橋美子", 32, "人事部"));
updateStatus("サンプルデータを読み込みました");
}
private void showError(String message) {
JOptionPane.showMessageDialog(this, message, "エラー", JOptionPane.ERROR_MESSAGE);
}
private void updateStatus(String message) {
statusLabel.setText(message);
Timer timer = new Timer(3000, e -> statusLabel.setText("準備完了"));
timer.setRepeats(false);
timer.start();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> {
new DataManagementApp().setVisible(true);
});
}
}
// Personクラス - データモデル
class Person {
private String name;
private int age;
private String department;
public Person(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
// ゲッター
public String getName() { return name; }
public int getAge() { return age; }
public String getDepartment() { return department; }
// セッター
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public void setDepartment(String department) { this.department = department; }
}
// PersonTableModel - テーブルモデル(MVCのModel)
class PersonTableModel extends AbstractTableModel {
private final String[] columnNames = {"名前", "年齢", "部署"};
private final List<Person> persons = new ArrayList<>();
@Override
public int getRowCount() {
return persons.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person person = persons.get(rowIndex);
switch (columnIndex) {
case 0: return person.getName();
case 1: return person.getAge();
case 2: return person.getDepartment();
default: return null;
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0: return String.class;
case 1: return Integer.class;
case 2: return String.class;
default: return Object.class;
}
}
public void addPerson(Person person) {
persons.add(person);
fireTableRowsInserted(persons.size() - 1, persons.size() - 1);
}
public void removePerson(int rowIndex) {
persons.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
public void updatePerson(int rowIndex, Person person) {
persons.set(rowIndex, person);
fireTableRowsUpdated(rowIndex, rowIndex);
}
public Person getPersonAt(int rowIndex) {
return persons.get(rowIndex);
}
public List<Person> getAllPersons() {
return new ArrayList<>(persons);
}
}
イベントハンドリング
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EventHandlingExample {
private JLabel counterLabel;
private int counter = 0;
public EventHandlingExample() {
createGUI();
}
private void createGUI() {
JFrame frame = new JFrame("Event Handling Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
// カウンター表示ラベル
counterLabel = new JLabel("カウンター: 0");
counterLabel.setFont(new Font("Arial", Font.BOLD, 16));
// インクリメントボタン
JButton incrementButton = new JButton("増加");
incrementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
updateCounterLabel();
}
});
// デクリメントボタン(ラムダ式使用)
JButton decrementButton = new JButton("減少");
decrementButton.addActionListener(e -> {
counter--;
updateCounterLabel();
});
// リセットボタン(メソッド参照使用)
JButton resetButton = new JButton("リセット");
resetButton.addActionListener(this::resetCounter);
// コンポーネントを追加
frame.add(counterLabel);
frame.add(incrementButton);
frame.add(decrementButton);
frame.add(resetButton);
frame.setSize(300, 150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void updateCounterLabel() {
counterLabel.setText("カウンター: " + counter);
}
private void resetCounter(ActionEvent e) {
counter = 0;
updateCounterLabel();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new EventHandlingExample());
}
}
データ表示(JTable)
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class TableExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Table Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// テーブルモデルの作成
String[] columnNames = {"ID", "名前", "年齢", "部署"};
Object[][] data = {
{1, "田中太郎", 30, "開発"},
{2, "佐藤花子", 28, "営業"},
{3, "鈴木一郎", 35, "企画"},
{4, "高橋美子", 32, "人事"}
};
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
JTable table = new JTable(tableModel);
// テーブルの設定
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
// スクロールペインに配置
JScrollPane scrollPane = new JScrollPane(table);
// ボタンパネル
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addButton = new JButton("追加");
addButton.addActionListener(e -> {
Object[] newRow = {tableModel.getRowCount() + 1, "新規", 25, "未定"};
tableModel.addRow(newRow);
});
JButton deleteButton = new JButton("削除");
deleteButton.addActionListener(e -> {
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) {
tableModel.removeRow(selectedRow);
}
});
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
// レイアウト
frame.setLayout(new BorderLayout());
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
カスタムダイアログ
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Dialog Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4, 1, 5, 5));
// メッセージダイアログボタン
JButton messageButton = new JButton("メッセージダイアログ");
messageButton.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "これはメッセージです", "情報", JOptionPane.INFORMATION_MESSAGE);
});
// 確認ダイアログボタン
JButton confirmButton = new JButton("確認ダイアログ");
confirmButton.addActionListener(e -> {
int result = JOptionPane.showConfirmDialog(frame, "削除してもよろしいですか?", "確認", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(frame, "削除されました");
}
});
// 入力ダイアログボタン
JButton inputButton = new JButton("入力ダイアログ");
inputButton.addActionListener(e -> {
String input = JOptionPane.showInputDialog(frame, "名前を入力してください:", "入力", JOptionPane.QUESTION_MESSAGE);
if (input != null && !input.trim().isEmpty()) {
JOptionPane.showMessageDialog(frame, "こんにちは、" + input + "さん!");
}
});
// カスタムダイアログボタン
JButton customButton = new JButton("カスタムダイアログ");
customButton.addActionListener(e -> {
showCustomDialog(frame);
});
panel.add(messageButton);
panel.add(confirmButton);
panel.add(inputButton);
panel.add(customButton);
frame.add(panel);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
private static void showCustomDialog(JFrame parent) {
JDialog dialog = new JDialog(parent, "カスタムダイアログ", true);
dialog.setLayout(new BorderLayout());
// 入力フィールド
JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5));
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
inputPanel.add(new JLabel("名前:"));
JTextField nameField = new JTextField();
inputPanel.add(nameField);
inputPanel.add(new JLabel("年齢:"));
JTextField ageField = new JTextField();
inputPanel.add(ageField);
// ボタンパネル
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton okButton = new JButton("OK");
JButton cancelButton = new JButton("キャンセル");
okButton.addActionListener(e -> {
String name = nameField.getText();
String age = ageField.getText();
JOptionPane.showMessageDialog(dialog, "名前: " + name + ", 年齢: " + age);
dialog.dispose();
});
cancelButton.addActionListener(e -> dialog.dispose());
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
dialog.add(inputPanel, BorderLayout.CENTER);
dialog.add(buttonPanel, BorderLayout.SOUTH);
dialog.setSize(300, 150);
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
}
}
ファイル操作
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class FileOperationExample {
private JTextArea textArea;
private JFrame frame;
public FileOperationExample() {
createGUI();
}
private void createGUI() {
frame = new JFrame("File Operation Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// メニューバーの作成
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("ファイル");
JMenuItem openItem = new JMenuItem("開く");
openItem.addActionListener(this::openFile);
JMenuItem saveItem = new JMenuItem("保存");
saveItem.addActionListener(this::saveFile);
JMenuItem exitItem = new JMenuItem("終了");
exitItem.addActionListener(e -> System.exit(0));
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
// テキストエリア
textArea = new JTextArea();
textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void openFile(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("テキストファイル", "txt"));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
textArea.setText("");
String line;
while ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, "ファイルの読み込みエラー: " + ex.getMessage(), "エラー", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveFile(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("テキストファイル", "txt"));
int result = fileChooser.showSaveDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (!file.getName().endsWith(".txt")) {
file = new File(file.getAbsolutePath() + ".txt");
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(textArea.getText());
JOptionPane.showMessageDialog(frame, "ファイルが保存されました", "保存完了", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, "ファイルの保存エラー: " + ex.getMessage(), "エラー", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
// システムのルックアンドフィールを使用
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> new FileOperationExample());
}
}