本人要做一个好友信息记录,打算在(性别)这个属性中设计单选按钮,在性别(男,女)中只能选中一个,即是选中(男)按钮,就不会选中(女)按钮,否则,反之。请高手指点一下怎么实现这个功能?

解决方案 »

  1.   

    建议你自己去看API,关键字JRadioButton
      

  2.   

    GUI Tutorial
    JRadioButton
      

  3.   

    如何设置单选按钮互斥?
    使用ButtonGroup类即可:
    ButtonGroup bGroup = new ButtonGroup();
    bGroup.add(jrbMale);
    bGroup.add(jrbFemale);
    即可.注意:ButtonGroup并不是java.awt.component的子类,因此不能添加到容器中!
      

  4.   

    新建一个   ButtonGroup sex   把你设置的 JRadioButton 放进ButtonGroup里  就能实现你的功能了
      

  5.   

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class test extends JFrame implements ActionListener{
    private JPanel testJPanel;
    private JRadioButton man;
    private JRadioButton lady;
    private ButtonGroup sex;

    public void testframe(){

    testJPanel=new JPanel();



     //性别选项加入容器
    man=new JRadioButton("男",true);
    man.setBounds(150,250,50,20);
    man.setBackground(Color.decode("#ffe7ba"));
    lady=new JRadioButton("女");
    lady.setBounds(200,250,50,20);
    lady.setBackground(Color.decode("#ffe7ba"));
    sex=new ButtonGroup();

    sex.add(man);
    sex.add(lady);

    testJPanel.add(man);
    testJPanel.add(lady);

    this.add(testJPanel);

    this.setSize(400,500);
    this.setVisible(true);



    }

    public void actionPerformed(ActionEvent be){

    }
    public static void main(String args[]){
    test a=new test();
    a.testframe();
    }
    }
      

  6.   


    //创建选择的选项
      
    r1=new JRadioButton("老婆");
    r2=new JRadioButton("情人");
    r3=new JRadioButton("二奶");
    //创建默认选项
    r4=new JRadioButton("以上都不喜欢",true);
      
    //创建ButtonGroup对象,不然就可以多选了,我们要的时单选
    ButtonGroup bg=new ButtonGroup();
      
    //在ButtonGroup中加入JRadioButton
    bg.add(r1);
    bg.add(r2);
    bg.add(r3);
    bg.add(r4);
      

  7.   

    放在同一个group里才是互斥的