swingコンポーネント->JRadioButton
JRadioButtonはJCheckBoxと同じように選択されているかされていないかの状態をもつボタンです。丸く小さなアイコンイメージを持ち選択された状態では 黒い丸が付きます。
ButtonGroupに入れるとグループの中では同時に一つだけしか選択できないようにできます。


コンストラクタ(抜粋)
JRadioButton()
 ラベルのないラジオボタンを生成します。
JRadioButton(String str)
 文字列strをラベルに持つラジオボタンを生成します。
JRadioButton(Icon icon)
 アイコンイメージのラジオボタンを生成します。
JRadioButton(String str, boolean state)
 文字列strをラベルにもち、初期値をstateで設定したラジオボタンを生成します。
 stateをtrueにするとチェックの付いた状態が初期状態になります。(デフォルトはfalseです)
メソッド(抜粋)
void setText(String str)
 文字列strを設定します。
void getText()
 表示されている文字列を取得します。
Icon getIcon()
 表示されている画像を取得します。
void setSelectedIcon(Icon icon)
 選択された時の画像iconを設定します。
void setIcon(Icon icon)
 選択されていない時の画像iconを設定します。

クリック

JRadioButtonSample.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonSample extends JFrame {
   Container contentPane;
    JRadioButton chk1 = new
                JRadioButton("ラジオボタン1");
← @空のインスタンスを生成
    JRadioButton chk2 = new
                JRadioButton("ラジオボタン2");
  public JRadioButtonSample() {
     super(JRadioButtonSample);
     addWindowAdapter(new WindowListener() {
       public void windowClosing(WindowEvent e) {
          System.exit(0);
       }
     });
     contentPane = getContentPane();
     contentPane.setLayout(new GridLayout(2,1));
     contentPane.add(chk1);
     contentPane.add(chk2);
      chk2.setIcon(new ImageIcon("img0.gif")); ← A選択されていない時の画像設定
      chk2.setSelectedIcon(new ImageIcon("img1.gif")); ← B選択されている時の画像設定
     setSize(200,200);
     setVisible(true);
   }
  public static void main(String[] args) {
   JRadioButtonSample myClass =
                  new JRadioButtonSample();
    }
}
@JRadioButton chk1 = new JRadioButton("ラジオボタン1");
 
チェックボックスのインスタンスを生成しています。
Achk2.setIcon(new ImageIcon("img0.gif"));
 JCheckBox(chk2)が選択されていない時の画像を設定します。
Bchk2.setSelectedIcon(new ImageIcon("img1.gif"));
 JCheckBox(chk2)が選択されている時の画像を設定します。
もどる