首頁常見問題正文

Java培訓(xùn):JRadioButton單選按鈕組件的用法

更新時間:2023-12-19 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

  JRadioButton組件稱為單選按鈕組件,單選按鈕只能選中一個,就像收音機上的電臺控制按鈕,當(dāng)按下一個按鈕時,先前按下的按鈕就會自動彈起。

  對于JRadioButton按鈕來說,當(dāng)一個按鈕被選中時,先前被選中的按鈕就需要自動取消選中,但是JRadioButton組件本身并不具備這種功能,若想實現(xiàn)JRadioButton按鈕之間的互斥,需要使用javax.swing.ButtonGroup類。ButtonGroup是一個不可見的組件,不需要將其添加到容器中顯示,只是在邏輯上表示一個單選按鈕組。將多個JRadioButton按鈕添加到同一個單選按鈕組中就能實現(xiàn)JRadioButton按鈕的單選功能。

  JRadioButton的常用構(gòu)造方法如表11-16所示。

  表11-16 JRadioButton的常用構(gòu)造方法

1702948988367_JRadioButton的常用構(gòu)造方法.jpg

  接下來,筆者通過一個完整的案例來演示下JRadioButton單選按鈕組件的基本用法:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RadioButtonExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("單選按鈕示例");
        frame.setLayout(new FlowLayout());

        JRadioButton radioButton1 = new JRadioButton("選項 1");
        JRadioButton radioButton2 = new JRadioButton("選項 2");

        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);

        radioButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 處理選擇選項 1 的操作
                System.out.println("選項 1 被選擇");
            }
        });

        radioButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 處理選擇選項 2 的操作
                System.out.println("選項 2 被選擇");
            }
        });

        frame.add(radioButton1);
        frame.add(radioButton2);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}

  這個示例演示了如何創(chuàng)建單選按鈕、將它們分組、將它們添加到容器中,并監(jiān)聽用戶的選擇事件。

  本文版權(quán)歸黑馬程序員Java培訓(xùn)學(xué)院所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明作者出處。謝謝!

  作者:黑馬程序員Java培訓(xùn)學(xué)院

  首發(fā):https://java.itheima.com

分享到:
在線咨詢 我要報名
和我們在線交談!