单选按钮 JradioButton 和复选框 JcheckBox 的使用

package first;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
class BRTest extends JFrame implements ItemListener,ActionListener
{
	JTextField text=new JTextField(15);///文本框,显示的是当前选中的复选或单选框中的内容
	BRTest(String s)
	{
		setSize(300,300);
		setVisible(true);
		setTitle(s);
		setLayout(new FlowLayout());
		///添加三个复选框
		JCheckBox cb1=new JCheckBox("c语言");
		cb1.addItemListener(this);
		add(cb1);
		JCheckBox cb2=new JCheckBox("c++语言");
		cb2.addItemListener(this);
		add(cb2);
		JCheckBox cb3=new JCheckBox("java语言");
		cb3.addItemListener(this);
		add(cb3);
		///添加三个单选按钮
		JRadioButton b1=new JRadioButton("鲜花");
		b1.addActionListener(this);
		add(b1);
		JRadioButton b2=new JRadioButton("鼓掌");
		b2.addActionListener(this);
		add(b2);
		JRadioButton b3=new JRadioButton("鸡蛋");
		b3.addActionListener(this);
		add(b3);
		///定义按钮组,单选按钮只有放到按钮组中才能实现单选功能
		ButtonGroup bg=new ButtonGroup();
		bg.add(b1);
		bg.add(b2);
		bg.add(b3);
		add(text);
		validate();
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		text.setText(e.getActionCommand());
	}
	public void itemStateChanged(ItemEvent ie) {
		// TODO Auto-generated method stub
		JCheckBox cb=(JCheckBox)ie.getItem();
		text.setText(cb.getText());
	}
}
public class Test  
{
	public static void main(String[] args) 
	{
	   new BRTest("单选按钮和复选框示例");
	}
}
原文地址:https://www.cnblogs.com/cmmdc/p/6853262.html