グループ内にあるすべてのラジオボタンを非選択にする

ラジオボタンをグループにまとめた場合に、いずれかのラジオボタンを一度選択状態にすると同じラジオボタンをクリックしても非選択の状態になりません。グループ内のすべてのラジオボタンを非選択の状態に戻すにはメソッドを使って設定が必要です。ここではグループ内のラジオボタンをすべて非選択にする方法について解説します。

(2022 年 04 月 11 日公開 / 2022 年 04 月 11 日更新)

グループ内のラジオボタンをすべて非選択にする

グループ内のすべてのラジオボタンを非選択の状態にするには ButtonGroup クラスで定義されている clearSelection メソッドを使います。

public void clearSelection()

選択をクリアして、ButtonGroup内のボタンが1つも選択されていない状態にします。

メソッドを実行すると、グループ内に含まれるすべてのラジオボタンは非選択の状態となります。

実際の使い方は次のようになります。

JRadioButton radio1 = new JRadioButton("Apple");
JRadioButton radio2 = new JRadioButton("Orange");

ButtonGroup bgroup = new ButtonGroup();
bgroup.add(radio1);
bgroup.add(radio2);

bgroup.clearSelection();

サンプルプログラム

それでは簡単なサンプルプログラムを作って試してみます。テキストエディタで次のように記述したあと、 JSample4_1.java という名前で保存します。

import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class JSample4_1 extends JFrame implements ActionListener{
  ButtonGroup bgroup;

  public static void main(String args[]){
    JSample4_1 frame = new JSample4_1("MyTitle");
    frame.setVisible(true);
  }

  JSample4_1(String title){
    setTitle(title);
    setBounds(100, 100, 600, 400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JRadioButton radio1 = new JRadioButton("Apple");
    JRadioButton radio2 = new JRadioButton("Orange");
    JRadioButton radio3 = new JRadioButton("Peach");

    bgroup = new ButtonGroup();
    bgroup.add(radio1);
    bgroup.add(radio2);
    bgroup.add(radio3);

    JPanel p = new JPanel();
    p.add(radio1);
    p.add(radio2);
    p.add(radio3);

    JButton button = new JButton("Clear");
    button.addActionListener(this);

    JPanel button_panel = new JPanel();
    button_panel.add(button);

    Container contentPane = getContentPane();
    contentPane.add(p, BorderLayout.CENTER);
    contentPane.add(button_panel, BorderLayout.SOUTH);
  }

  public void actionPerformed(ActionEvent e){
    bgroup.clearSelection();
  }
}

次のようにコンパイルを行います。

javac JSample4_1.java

グループ内のラジオボタンをすべて非選択にする(1)

コンパイルが終わりましたら実行します。

java JSample4_1

ラジオボタンを 3 つとボタンを 1 つ追加しました。ラジオボタンはすべて同じグループに追加されています。

グループ内のラジオボタンをすべて非選択にする(2)

同じグループ内にあるラジオボタンは一度どれかのラジオボタンが選択状態になると、他のラジオボタンをクリックすればそのラジオボタンが選択状態になりますし、選択状態のラジオボタンをもう一度クリックしても非選択とはなりません。

グループ内のラジオボタンをすべて非選択にする(3)

画面下にあるボタンをクリックすると、グループ内のすべてのラジオボタンが非選択となります。

グループ内のラジオボタンをすべて非選択にする(4)

-- --

グループ内のラジオボタンをすべて非選択にする方法について解説しました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。