我正在尝试用下面的代码将当前日期和第二天的日期放在一个JComboBox中
private void dateCombo(){
Calendar cal = new GregorianCalendar();
int month =cal.get(Calendar.MONTH);
int year =cal.get(Calendar.YEAR);
int day =cal.get(Calendar.DAY_OF_MONTH);
cmb_date.addItem(+year+"-"+(month+1)+"-"+day);
cmb_date.addItem(+year+"-"+(month+1)+"-"+(day+1));
}但是它以'yyyy-m-d‘格式显示日期,而我希望它以'yyyy-mm-dd’格式显示。
我想我可以用
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
txt_date.setText(sdf.format(date));以'yyyy-mm-dd‘格式获取当前日期,但是如何处理第二天的日期呢?
发布于 2013-02-10 11:23:08
您应该将Date对象添加到JComboBox中,而不是将当前日期和第二天的日期添加到字符串中,然后使用自定义的ListCellRenderer以所需格式呈现日期。
示例代码:
import java.awt.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
public class DateComboExample {
// Create Date Renderer for formatting Date
public static class DateComboBoxRenderer extends DefaultListCellRenderer {
// desired format for the date
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus ) {
Object item = value;
// if the item to be rendered is date then format it
if( item instanceof Date ) {
item = dateFormat.format( ( Date ) item );
}
return super.getListCellRendererComponent( list, item, index, isSelected, cellHasFocus);
}
}
public static void main( String[] str ) {
JComboBox combo = new JComboBox();
// Add current date
GregorianCalendar calendar = new GregorianCalendar();
combo.addItem( calendar.getTime() );
// Add Next date
calendar.roll( GregorianCalendar.DAY_OF_MONTH, 1 );
combo.addItem( calendar.getTime() );
// Set Renderer for formating the date in combobox
combo.setRenderer( new DateComboBoxRenderer() );
JFrame frame = new JFrame( "Date Rendere Example" );
JPanel panel = new JPanel();
panel.add( new JLabel( "Date Combo: ") );
panel.add( combo );
frame.add( panel );
frame.pack();
frame.setVisible( true );
}
}https://stackoverflow.com/questions/14793146
复制相似问题