JavaSwing:JRadioButton-单选按钮开发详解

在这里插入图片描述
单选按钮的实现-可以选择或取消选择的项目,并向用户显示其状态。

与ButtonGroup对象一起使用以创建一组按钮,其中一次只能选择一个按钮。
(创建一个ButtonGroup对象,并使用其add方法在该组中包括JRadioButton对象。)
在这里插入图片描述
注意:ButtonGroup对象是一个逻辑分组,而不是物理分组。
要创建按钮面板,仍然应该创建一个JPanel或类似的container-object,并向其添加javax.swing.border.Border,以使其与周围的component分离。
可以通过操作配置按钮,并在某种程度上控制按钮。除了直接配置按钮外,将Action与按钮配合使用还有很多好处。

构造方法:

  • 无文本,未选中
    JRadioButton()

  • 有文本,未选中
    JRadioButton(String text)
    在这里插入图片描述

  • 有文本,并指定是否选中
    JRadioButton(String text, boolean selected)

方法

// 设置单选按钮的 文本、字体 和 字体颜色
void setText(String text)
void setFont(Font font)
void setForeground(Color fg)

/* 以下方法定义在 javax.swing.AbstractButton 基类中 */

// 设置单选按钮是否选中状态
void setSelected(boolean b)

// 判断单选按钮是否选中
boolean isSelected()

// 设置单选按钮是否可用
void setEnabled(boolean enable)

// 设置单选按钮在 默认、被选中、不可用 时显示的图片
void setIcon(Icon defaultIcon)
void setPressedIcon(Icon pressedIcon)
void setDisabledIcon(Icon disabledIcon)

// 设置图片和文本的间距
void setIconTextGap(int iconTextGap)

监听器:

在这里插入图片描述

  • 添加状态改变监听器
    void addChangeListener(ChangeListener l)

ButtonGroup(按钮组):

当有多个单选按钮时,一般只允许一个单选按钮选中,因此需要对同一类型的单选按钮进行分组,如下:

// 创建一个按钮组
ButtonGroup btnGroup = new ButtonGroup();

// 添加单选按钮到按钮组
btnGroup.add(radioBtn01);
btnGroup.add(radioBtn02);

代码实例

在这里插入图片描述

原创文章 497 获赞 1735 访问量 84万+

猜你喜欢

转载自blog.csdn.net/qq_33589510/article/details/105862805