1、编写一个Application程序,其中包括一个单选按钮组(男生/女生)和一个标签,要求实现的功能是:
(1)用户利用单选按钮组选择性别后,在下面的标签中显示用户的选择结果;
(2)窗口可以通过点击窗口右上角自带的“关闭”按钮而关闭。
------解决方案--------------------------------------------------------
public class Demo extends JFrame
{
private JLabel lblNewLabel;
public static void main(String[] args)
{
new Demo().setVisible(true);
}
public Demo()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BoxLayout(getContentPane(),
BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
final JRadioButton rdbtnNewRadioButton = new JRadioButton("男");
rdbtnNewRadioButton.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (rdbtnNewRadioButton.isSelected())
{
lblNewLabel.setText(rdbtnNewRadioButton.getText());
}
}
});
getContentPane().add(rdbtnNewRadioButton);
final JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("女");
rdbtnNewRadioButton_1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (rdbtnNewRadioButton_1.isSelected())
{
lblNewLabel.setText(rdbtnNewRadioButton_1.getText());
}
}
});
bg.add(rdbtnNewRadioButton_1);
bg.add(rdbtnNewRadioButton);
getContentPane().add(rdbtnNewRadioButton_1);
lblNewLabel = new JLabel(" ");
getContentPane().add(lblNewLabel);
}
}