TOP →
Java →
Swing →
JRadioButton → This Page
JRadioButton@Swing サンプル08
概要
Java -
Swing -
JRadioButton のサンプルです。
・クリックイベント
・選択状態取得
解説
クリックイベントを実現するには ActionListener を implements したクラスにする必要があります。
ActionListener を implements すると、actionPerformed メソッドを実装する必要があります。
このメソッドにイベントの処理内容を記述します。
また、addActionListener メソッドでラジオボタンからのイベントが受け取れるようにアクションリスナーの追加を行います。
今回のサンプルではクリックされたラジオボタンによって、テキスト1に文字列を
テキスト2にラジオボタンの状態を表示するものにしています。
サンプルイメージ
サンプルソース
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JRadioButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* JRadioButton サンプル08
* ・クリックイベント
* ・ラジオボタン状態取得
*
* @author みっちー
*/
public class JRadioButton08 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
/** イベント表示テキスト */
JTextField textE = null;
/** ラジオボタン表示テキスト */
JTextField textC = null;
/**
* 開始メソッド
*
* @param args パラメータ
*/
public static void main(String[] args) {
JRadioButton08 frame = new JRadioButton08();
// 閉じるボタンをクリックされた場合の動作を設定
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウインドウのタイトルを設定
frame.setTitle("JRadioButton サンプル08");
// フレームの X座標、Y座標、幅、高さを設定
frame.setBounds(100, 200, 400, 150);
// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
frame.setVisible(true);
}
/**
* コンストラクタ
*/
public JRadioButton08() {
// パネルを作成
JPanel panelBase = new JPanel();
// ラジオボタンを作成
JRadioButton radio1 = new JRadioButton("AAAAA");
JRadioButton radio2 = new JRadioButton("BBBBB");
JRadioButton radio3 = new JRadioButton("CCCCC");
// アクションリスナー追加
radio1.addActionListener(this);
radio2.addActionListener(this);
radio3.addActionListener(this);
// テキストを作成
textE = new JTextField(20);
textC = new JTextField(20);
// ラジオボタン・テキストを追加
panelBase.add(radio1);
panelBase.add(radio2);
panelBase.add(radio3);
panelBase.add(textE);
panelBase.add(textC);
// パネルを追加
getContentPane().add(panelBase);
}
/**
* アクション
*/
public void actionPerformed(ActionEvent e) {
// クリックされたラジオボタンのイベントを取得
if (e.getActionCommand().equals("AAAAA")) {
textE.setText("AAAAA がクリックされた!");
} else if (e.getActionCommand().equals("BBBBB")) {
textE.setText("BBBBB がクリックされた!");
} else if (e.getActionCommand().equals("CCCCC")) {
textE.setText("CCCCC がクリックされた!");
}
// クリックされたラジオボタンの状態を取得
JRadioButton radio = (JRadioButton)e.getSource();
if (radio.isSelected()) {
textC.setText(e.getActionCommand() + "は選択状態");
} else {
textC.setText(e.getActionCommand() + "は未選択状態");
}
}
}
サンプルソースのダウンロード
ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)
更新履歴
2016/05/13 Windows 8.1 + Java 7 環境で全体を見直し
2008/01/23 新規作成
TOP →
Java →
Swing →
JRadioButton → This Page