Java如何为单选按钮创建ButtonGroup?
本示例说明如何创建一个ButtonGroup将单选按钮组件分组为一个组的。在此示例中,您还可以看到我们向单选按钮添加了一个动作监听器。
package org.nhooo.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonGroupDemo extends JFrame {
public ButtonGroupDemo() {
initializeUI();
}
private void initializeUI() {
setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
//为我们的单选按钮创建一个动作监听器。
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JRadioButton button = (JRadioButton) e.getSource();
System.out.println("You select button: " + button.getText());
}
};
//创建四个单选按钮并设置动作侦听器。
JRadioButton button1 = new JRadioButton("One");
button1.addActionListener(action);
JRadioButton button2 = new JRadioButton("Two");
button2.addActionListener(action);
JRadioButton button3 = new JRadioButton("Three");
button3.addActionListener(action);
JRadioButton button4 = new JRadioButton("Four");
button4.addActionListener(action);
//创建一个ButtonGroup将单选按钮分组为一组。这个
//将确保在菜单上仅选择一项或一项收音机
//组。
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
group.add(button3);
group.add(button4);
getContentPane().add(button1);
getContentPane().add(button2);
getContentPane().add(button3);
getContentPane().add(button4);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonGroupDemo().setVisible(true);
}
});
}
}
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短