马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
新手上路,请多关照。
使用下拉列表,下拉列表监听器失去作用。
代码如下:
package com.zsgc.jframe;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* @author 23203 增加学生信息的窗体
*
*/
public class InsertFrane extends JFrame implements ItemListener { // ItemListener
// 下拉列表监听器
private JPanel panel1, panel2, panel3, panel4, panel5;
private JComboBox<String> comboBox1, comboBox2, comboBox3, comboBox4,
comboBox5;
private String nation[] = { "汉", "白", "傣", "蒙古族", "水族", "维吾尔族", "美" };
private String sex[] = { "男", "女" };
private int START_YEAR = 1980;
private int END_YEAR = 2010;
public static void main(String[] args) {
InsertFrane A = new InsertFrane();
A.setVisible(true);
A.pack();
}
public InsertFrane() {
comboBox1 = new JComboBox<String>(nation);
comboBox2 = new JComboBox<String>(sex);
comboBox3 = new JComboBox<String>();
comboBox4 = new JComboBox<String>();
comboBox5 = new JComboBox<String>();
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
panel5 = new JPanel();
setTitle("增加学生信息");
setLocation(200, 200);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 1));
panel1.add(new JLabel("学号:"));
panel1.add(new JTextField(10));
panel2.add(new JLabel("姓名:"));
panel2.add(new JTextField(10));
panel3.add(new JLabel("专业:"));
panel3.add(new JTextField(10));
panel4.add(new JLabel("民族:"));
panel4.add(comboBox1);
panel4.add(new JLabel(" 性别:"));
panel4.add(comboBox2);
panel5.add(new JLabel("生日:年:"));
panel5.add(comboBox3);
panel5.add(new JLabel("月:"));
panel5.add(comboBox4);
panel5.add(new JLabel("日:"));
panel5.add(comboBox5);
add(panel1);
add(panel2);
add(panel3);
add(panel4);
add(panel5);
// 初始化年月日
for (int i = START_YEAR; i <= END_YEAR; i++) {
comboBox3.addItem("" + i);
}// 初始化年份
for (int i = 1; i <= 12; i++) {
comboBox4.addItem("" + i);
}// 初始化月份
for (int i = 1; i <= 31; i++) {
comboBox5.addItem("" + i);
}// 初始化号
}
/**
* 下拉列表事件,解决闰年二月份问题
*/
@Override
public void itemStateChanged(ItemEvent arg0) {
int data = 31;
Object obj = comboBox4.getSelectedItem(); // getSelectedItem()方法,返回当前下拉列表的值(以对象的形式返回)
// 取得当前月份
if (obj != null)
comboBox5.removeAllItems();// removeAllItems()方法,删除掉下拉列表的所有的项目,清空掉日
int mouth = Integer.valueOf(obj.toString());// 将对象(月份)变为整数
if (mouth == 4 || mouth == 6 || mouth == 9 || mouth == 11) {
data = 30;
} else if (mouth == 2) {
int year = Integer.valueOf(comboBox3.getSelectedItem().toString());// 取得当前年号
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))// 是闰年
data = 29;
else
data = 28;
}
for (int i = 1; i <= data; i++) {
comboBox5.addItem("" + i);
}// 添加号
}
}
感谢大神帮助。
我大概看了下,原因出在你没有注册监听器,在你上面给的代码的第86行空处添加一句
comboBox4.addItemListener(this);
即可解决
|