1.一个简单的注册界面程序
·
一开始单选框两个框都可以选,后来发现是没有将选项框加入到ButtonGroup里面。加进去之后就可以只能单选了
2.代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class enroll extends JFrame implements ActionListener
{
JPanel jp = new JPanel();
//标签数组
JLabel[] jlArray = {new JLabel("性别"),new JLabel("爱好"),new JLabel("输入内容为:")};
//单选框数组
JRadioButton[] jrbArray = {new JRadioButton("男"), new JRadioButton("女")};
//复选框数组
JCheckBox[] jcbArray = {new JCheckBox("健身"),new JCheckBox("上网")};
//按钮数组
JButton[] jbArray = {new JButton("提交"),new JButton("清空")};
//文本框
JTextField jtf =new JTextField();
//按钮组
ButtonGroup bg = new ButtonGroup();
//构造器
public enroll()
{
//设置布局管理器
jp.setLayout(null);
//对控件进行设置
for(int i = 0;i<2;i++)
{
//设置各个控件的大小和位置
jlArray[i].setBounds(20, 20+i*50, 80, 30);
jrbArray[i].setBounds(40+i*100, 40,80,30);
jcbArray[i].setBounds(40+i*100, 100,80,30);
jbArray[i].setBounds(400+i*120,200,80,26);
//把单选框添加到按钮组中
bg.add(jrbArray[i]);
//给单选框和复选框、按钮添加监听事件
jrbArray[i].addActionListener(this);
jcbArray[i].addActionListener(this);
jbArray[i].addActionListener(this);
//添加带jpanel中
jp.add(jlArray[i]);
jp.add(jrbArray[i]);
jp.add(jcbArray[i]);
jp.add(jbArray[i]);
}
jlArray[2].setBounds(20,150,120,30);
jp.add(jlArray[2]);
jtf.setBounds(120,150,500,26);
jp.add(jtf);
//设置文本框为不可编辑状态
jtf.setEditable(false);
this.add(jp);
//设置窗体的属性
this.setTitle("注册页面");
this.setBounds(100, 100, 700, 280);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource()==jbArray[1])
{
//清空按钮执行的动作
bg.clearSelection();
for(int i=0;i<2;i++)
jcbArray[i].setSelected(false);
jtf.setText("");
}
else
{
//两个临时字符串
StringBuffer temp1=new StringBuffer("你是一个");
StringBuffer temp2=new StringBuffer("");
for(int i=0;i<2;i++)
{
if (jrbArray[i].isSelected())
temp1.append(jrbArray[i].getText());
if (jcbArray[i].isSelected())
temp2.append(jcbArray[i].getText()+", ");
}
if (temp2.length()==0)
jtf.setText("兴趣爱好不能为空!!");
else
{
temp1.append("生,你比较喜欢");
temp1.append(temp2.substring(0, temp2.length()-2));
jtf.setText(temp1.append("。").toString());
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enroll e =new enroll();
}
}