ButtonGroup的添加问题,小菜求教!

weidu23 2013-02-03 03:38:34
首先,请看代码:

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。
以上代码是我的一个测试类代码!
...全文
561 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
weidu23 2013-02-04
  • 打赏
  • 举报
回复
引用 1 楼 zeko075 的回复:
Java code ? 123456789101112131415161718192021222324252627282930 import java.awt.FlowLayout; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JPanel; import java……
感谢 ...
zeko075 2013-02-03
  • 打赏
  • 举报
回复
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加油···

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧