package javademo; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class raius extends JFrame{ private Container container; private JLabel b1,b2; private JRadioButton rb1,rb2; private JTextField name; JTextArea ta=new JTextArea(); public raius() { container=this.getContentPane(); b1=new JLabel("请输入姓名"); name=new JTextField(8); b2=new JLabel("请选择姓名"); rb1=new JRadioButton("男"); rb2=new JRadioButton("女"); JPanel panel=new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.LEFT)); panel.add(b1); panel.add(name); panel.add(b2); panel.add(rb1); panel.add(rb2); rb1.addActionListener(new Listener()); rb2.addActionListener(new Listener());//注册事件监听程序 ButtonGroup bg1=new ButtonGroup(); bg1.add(rb1); bg1.add(rb2); this.add(BorderLayout.NORTH,panel); this.add(BorderLayout.SOUTH,ta); this.setTitle("JRadioButton演示程序"); this.setSize(600,450); this.show(); } class Listener implements ActionListener{ public void actionPerformed(ActionEvent e) { String str2=name.getText(); if(e.getSource()==rb1) { String str1=rb1.getText(); ta.setText("输入的学生信息为:\n"+"姓名:"+str2+"\n性别:"+str1); } else { String str1=rb2.getText(); ta.setText("输入的学生信息为:\n"+"姓名:"+str2+"\n性别:"+str2); } } } public static void main(String []args) { new raius(); } }
运行结果: