TOP →
Java →
Swing →
JOptionPane → This Page
JOptionPane@Swing サンプル07
概要
Java -
Swing -
JOptionPane のサンプルです。
・カスタム選択肢
解説
選択肢をカスタムしたダイアログです。
3番目の項目を初期選択にしています。
ただし、戻り値はインデックス(数値型)となります。
サンプルイメージ
メイン画面
ダイアログ
サンプルソース
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
/**
* JOptionPane サンプル07
* ・カスタム選択肢
*
* @author みっちー
*/
public class JOptionPane07 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel label;
/**
* 開始メソッド
*
* @param args パラメータ
*/
public static void main(String[] args) {
JOptionPane07 frame = new JOptionPane07();
// 閉じるボタンをクリックされた場合の動作を設定
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウインドウのタイトルを設定
frame.setTitle("JOptionPane サンプル07");
// フレームの X座標、Y座標、幅、高さを設定
frame.setBounds(100, 200, 400, 120);
// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
frame.setVisible(true);
}
/**
* コンストラクタ
*/
public JOptionPane07() {
// パネルを作成
JPanel panelBase = new JPanel();
// ボタンを作成
JButton button = new JButton("confirm");
// アクションリスナー追加
button.addActionListener(this);
// ラベルを生成
label = new JLabel();
label.setPreferredSize(new Dimension(100, 30));
label.setBorder(new BevelBorder(BevelBorder.RAISED));
// ボタン、ラベルを追加
panelBase.add(button);
panelBase.add(label);
// パネルを追加
getContentPane().add(panelBase);
}
/**
* アクション
*/
public void actionPerformed(ActionEvent e) {
String options[] = { "aaaaa", "bbbbb", "ccccc", "ddddd" };
int ret = JOptionPane.showOptionDialog(this, "confirm", "title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
label.setText(Integer.toString(ret));
}
}
サンプルソースのダウンロード
ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)
更新履歴
2016/08/27 新規作成
TOP →
Java →
Swing →
JOptionPane → This Page