日期:2014-05-20 浏览次数:20770 次
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * 这是JRadioButton使用的一个实例 * 获取JRadioButton的对应值感觉还是麻烦了一些,不知道有没有简单一些的方法? * @author GaoYong * */ public class JRadioButtonDemo1 extends JFrame{ private ButtonGroup genderGroup=null; private JRadioButton boyBtn=null; private JRadioButton girlBtn=null; public JRadioButtonDemo1(){} public JRadioButtonDemo1(String title){ super(title); boyBtn=new JRadioButton("boy"); girlBtn=new JRadioButton("girl"); genderGroup=new ButtonGroup(); genderGroup.add(boyBtn); genderGroup.add(girlBtn); this.getContentPane().setLayout(new FlowLayout()); this.getContentPane().add(boyBtn); this.getContentPane().add(girlBtn); girlBtn.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub // genderGroup.getSelection().g System.out.println(girlBtn.getText()); System.out.println("girlBtn is selected is "+girlBtn.isSelected()); } }); boyBtn.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub System.out.println(boyBtn.getText()); System.out.println("boyBtn is selected is "+boyBtn.isSelected()); } }); this.pack(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setVisible(true); } public static void main(String[] args){ new JRadioButtonDemo1("Demo"); } }
------解决方案--------------------
3楼正解、
------解决方案--------------------
3楼正解。
需要使用ButtonGroup这个东东