TOP →
Java →
Swing →
JOptionPane → This Page
JOptionPane@Swing サンプル04
概要
Java -
Swing -
JOptionPane のサンプルです。
・色々な選択ダイアログ
解説
選択1は通常の文字列をメッセージとして表示、
選択2はラベルをメッセージとして表示、
選択3はアイコン非表示、
選択4は自前のアイコンを表示しています。
サンプルイメージ
メイン画面
サンプルソース
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* JOptionPane サンプル04
* ・色々な選択ダイアログ
*
* @author みっちー
*/
public class JOptionPane04 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
/**
* 開始メソッド
*
* @param args パラメータ
*/
public static void main(String[] args) {
JOptionPane04 frame = new JOptionPane04();
// 閉じるボタンをクリックされた場合の動作を設定
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウインドウのタイトルを設定
frame.setTitle("JOptionPane サンプル04");
// フレームの X座標、Y座標、幅、高さを設定
frame.setBounds(100, 200, 420, 100);
// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
frame.setVisible(true);
}
/**
* コンストラクタ
*/
public JOptionPane04() {
// パネルを作成
JPanel panelBase = new JPanel();
// ボタンを作成
JButton button1 = new JButton("Confirm1");
JButton button2 = new JButton("Confirm2");
JButton button3 = new JButton("Confirm3");
JButton button4 = new JButton("Confirm4");
// アクションコマンドを設定
button1.setActionCommand("Confirm1");
button2.setActionCommand("Confirm2");
button3.setActionCommand("Confirm3");
button4.setActionCommand("Confirm4");
// アクションリスナー追加
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
// ボタンを追加
panelBase.add(button1);
panelBase.add(button2);
panelBase.add(button3);
panelBase.add(button4);
// パネルを追加
getContentPane().add(panelBase);
}
/**
* アクション
*/
public void actionPerformed(ActionEvent e) {
if ("Confirm1".equals(e.getActionCommand())) {
// 文字列を表示
JOptionPane.showConfirmDialog(this, "Confirm1");
} else if ("Confirm2".equals(e.getActionCommand())) {
// ラベルを使って表示
JLabel label = new JLabel("Confirm2");
label.setForeground(Color.RED);
JOptionPane.showConfirmDialog(this, label);
} else if ("Confirm3".equals(e.getActionCommand())) {
// タイトルも表示
JOptionPane.showConfirmDialog(this, "Confirm3", "title3", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
} else if ("Confirm4".equals(e.getActionCommand())) {
// アイコンも表示
ImageIcon icon = new ImageIcon("./img/00.png");
JOptionPane.showConfirmDialog(this, "Confirm4", "title4", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, icon);
}
}
}
サンプルソースのダウンロード
ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)
更新履歴
2016/08/27 新規作成
TOP →
Java →
Swing →
JOptionPane → This Page