swing學習4--添加單選、復選框並獲取其中的值


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);
            }
            
        });
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM