首先,请看代码:import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;public class Test extends JFrame{
Test(){
JPanel jpanel = new JPanel() ;
this.getContentPane().add(jpanel);

ButtonGroup bg = new ButtonGroup();
jpanel.add(bg); //这步错了,怎么改?

JRadioButton jrbUser = new JRadioButton("用户");
JRadioButton jrbAdmin = new JRadioButton("管理");
bg.add(jrbUser);
bg.add(jrbAdmin);
}
public static void main(String[] args) {
new Test();
}
}我知道jpanel.add(bg)错了,但是我的代码里真的需要在jpanel里面添加JRadioButton!我不知道怎么做,求教,求解惑!---另附---
我之前写一个代码,里面用GridLayout布局JFrame,然后在其中一个JPanel里要使用单选框JRadioButton,所以要用ButtonGroup。
以上代码是我的一个测试类代码!

解决方案 »

  1.   

    import java.awt.FlowLayout;
    import javax.swing.ButtonGroup;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    public class Test extends JFrame{
    Test(){
    JRadioButton jrbUser = new JRadioButton("用户");
    JRadioButton jrbAdmin = new JRadioButton("管理");
    JPanel jpanel = new JPanel();
    this.getContentPane().add(jpanel);
    setLayout(new FlowLayout());
    setSize(200,300);
    ButtonGroup bg = new ButtonGroup();
    // jpanel.add(bg); //这步错了,怎么改?
    add(jrbUser);
    add(jrbAdmin);
    bg.add(jrbUser);
    bg.add(jrbAdmin);
    setVisible(true);


    }

    public static void main(String[] args) {
    new Test();
    }
    }
    ButtonGroup不是一个组件所以不能添加到框架中。在API中写的也比较清楚
    add
    public Component add(Component comp)

    这是add方法的定义,其中的形参是Component的引用。而ButtonGroup是直接从Object中继承的(可以看一下ButtonGroup的继承关系),通过Component的引用当然是无法调用的。
    在API中也有介绍
    How to Use Radio Buttons
    Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected. The Swing release supports radio buttons with the JRadioButton and ButtonGroup classes. To put a radio button in a menu, use the JRadioButtonMenuItem class. Other ways of displaying one-of-many choices are combo boxes and lists. Radio buttons look similar to check boxes, but, by convention, check boxes place no limits on how many items can be selected at a time.Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual button characteristics, as discussed earlier in this section. For example, you can specify the image displayed in a radio button.ButtonGroup的直接拿过来用就行了,把几个RadioButton添加进去,而不需要把ButtonGroup添加到任何的组件。
    LZ以后还是遇到问题应该多看看API,API有时候可以解决很多问题,或者Google一下也能找到很多方法
    LZ加油···