如何直接用java Swing写日期下拉列表框

后面的月和日如何做?每个月的天数不一样!
2024-12-04 17:47:03
推荐回答(5个)
回答1:

DateDropFrame extends JFrame
给year和month添加一个ItemListener来实时计算指定年和月中有多少天就可以了.
代码是用Swing写的,不过看你的图,不像是Swing界面.
/**
* Create the frame.
*/
public DateDropFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));

final JComboBox year = new JComboBox();
year.setModel(new DefaultComboBoxModel(getModel(start, end)));
contentPane.add(year);

final JComboBox month = new JComboBox();
month.setModel(new DefaultComboBoxModel(getModel(1, 12)));
contentPane.add(month);

final JComboBox day = new JComboBox();
contentPane.add(day);

year.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
setDay(year, month, day);
}
});
month.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
setDay(year, month, day);
}
});
setDay(year, month, day);
setContentPane(contentPane);
}

/**
* calculate days in select month & year
*/
private void setDay(JComboBox year, JComboBox month, JComboBox day) {
int y = Integer.parseInt((String) year.getSelectedItem());
int m = Integer.parseInt((String) month.getSelectedItem());
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, y);
c.set(Calendar.MONTH, m - 1);
int days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
day.setModel(new DefaultComboBoxModel(getModel(1, days)));

}

/**
* get String array [start, end]
*/
private String[] getModel(int start, int end) {
String[] m = new String[end - start + 1];
for (int i = 0; i < m.length; i++) {
m[i] = String.valueOf(i + start);
}
return m;
}

回答2:

public static List reader_list;

reader_list = new List(shell, SWT.BORDER); //下拉框
reader_list.setBounds(int,int,int,int); //定位

String[] readerArray= new String[]{"2011","2012",2013"};
reader_list.setItems(readerArray); //赋值

回答3:

找一个Swingx的开源项目,里面有一个JDatePicker类,就是一个日历选择器。

回答4:

直接自己做一个日期时间组件就行了

回答5:

一.直接给出几个下拉列表放些值
二.去网上下个日期代码 选中文本框的时候显示一张日历表