swing学习3--添加单选、复选框并获取其中的值
package swing;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Test1 {
private static JPanel pane1,pane2 ;
public static void main(String[] args) {
JFrame frame = new JFrame(“复选框”);
frame.setSize(200,200);
//设置窗口布局
frame.setLayout(new GridLayout(3,1));
frame.setLocation(500,200);
pane1 = new JPanel();
pane2 = new JPanel();
JPanel pane3 = new JPanel();
//创建复选框组件
JCheckBox jcb1 = new JCheckBox(“足球”);
JCheckBox jcb2 = new JCheckBox(“篮球”);
JCheckBox jcb3 = new JCheckBox(“棑球”);
//创建单选框组件
JRadioButton jrb1 = new JRadioButton(“男”);
JRadioButton jrb2 = new JRadioButton(“nv “);
//创建单选框按钮组
ButtonGroup bg = new ButtonGroup();
JButton jb = new JButton(“按钮”);
pane3.add(jb);
pane1.add(jcb1);
pane1.add(jcb2);
pane1.add(jcb3);
//将单选框组件加入单选框按钮组,否则两个都可以选择
bg.add(jrb1);
bg.add(jrb2);
pane2.add(jrb1);
pane2.add(jrb2);
frame.add(pane1);
frame.add(pane2);
frame.add(pane3);
frame.setVisible(true);
//按钮监听事件
jb.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String info =””;
//通过面板属性名获取到该面板上的所有组件
for(Component c:pane1.getComponents()){
//通过 instanceof方法筛选复选框组件
if(c instanceof JCheckBox){
//判断复选框组件是否被选中
if(((JCheckBox) c).isSelected()){
//获取该复选框组件信息
info += ((JCheckBox)c).getText();
}
}
}
System.out.println(info);
info=””;
for(Component c:pane2.getComponents()){
if(c instanceof JRadioButton){
if(((JRadioButton) c).isSelected()){
info += ((JRadioButton)c).getText();
}
}
}
System.out.println(info);
}
});
}
}