package cn.hucu.swing;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class UserJFrame extends JFrame implements ActionListener {
private JTextArea textUser;
private int number=1;
private JTextField textNumber,textName;
private JRadioButton rbMale,rbFemale;//性别单选按钮
private JComboBox combProvince,combCity;
private JButton btnAdd;
private Object[][] cities;
public UserJFrame(Object[] provinces,Object[][] cities) {
super("输入学生信息");
setBounds(300, 230, 460, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout( new GridLayout(1, 2));
textUser = new JTextArea();
getContentPane().add( new JScrollPane(textUser) );
Font font = new Font("aa",Font.BOLD,18);
textUser.setFont(font);
textUser.setForeground(Color.RED);
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(6, 1));
textNumber = new JTextField("1");
textNumber.setEditable(false);
panel.add(textNumber);
textName = new JTextField("姓名");
panel.add(textName);
JPanel panelSex = new JPanel();
panel.add(panelSex);
panelSex.setLayout(new GridLayout(1, 2));
rbMale = new JRadioButton("男", true);
rbFemale = new JRadioButton("女");
panelSex.add(rbMale);
panelSex.add(rbFemale);
//要让多个RadioButton组成一组,得用ButtonGroup来组合
ButtonGroup group = new ButtonGroup();
group.add(rbMale);
group.add(rbFemale);
this.cities = cities;
combProvince = new JComboBox(provinces);
panel.add(combProvince);
combCity = new JComboBox(cities[0]);
panel.add(combCity);
combProvince.addActionListener(this);
btnAdd = new JButton("添加");
panel.add(btnAdd);
btnAdd.addActionListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==combProvince){
int i = combProvince.getSelectedIndex();
combCity.removeAllItems();
for(int j=0;j<cities[i].length;j++){
combCity.addItem( cities[i][j] );
}
}
if(e.getSource()==btnAdd){
Student s = new Student();
//学号---收集并更新界面上的第一个数据
s.setNumber(number);
number++;
textNumber.setText(""+number);
//姓名
s.setName( textName.getText() );
textName.setText("姓名");
//性别
String str=null;
if(rbMale.isSelected()){
str = rbMale.getText();
}
if(rbFemale.isSelected()){
str = rbFemale.getText();
}
s.setSex(str);
//省份
String strProv = (String) combProvince.getSelectedItem();
s.setProvince( strProv );
//城市
String strCity = (String) combCity.getSelectedItem();
s.setCity(strCity);
textUser.append( s.toString()+"
" );
}
}
public static void main(String[] args) {
Object[] provinces = {"湖南省","江苏省","浙江省","湖北省"};
Object[][] cities={
{"长沙市","益阳市","衡阳市","湘潭市"},
{"南京市","苏州市","无锡市"},
{"杭州市","宁波市","温州市","湖州市"},
{"武汉市","赤壁市","孝感市"}
};
new UserJFrame(provinces,cities);
}
}