首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在JComboBox中以'yyyy-mm-dd‘格式放置日期列表?

如何在JComboBox中以'yyyy-mm-dd‘格式放置日期列表?
EN

Stack Overflow用户
提问于 2013-02-10 08:12:53
回答 3查看 19.2K关注 0票数 1

我正在尝试用下面的代码将当前日期和第二天的日期放在一个JComboBox中

代码语言:javascript
运行
复制
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’格式显示。

我想我可以用

代码语言:javascript
运行
复制
Date date = new Date();
SimpleDateFormat  sdf = new SimpleDateFormat("yyyy/MM/dd");
txt_date.setText(sdf.format(date));

以'yyyy-mm-dd‘格式获取当前日期,但是如何处理第二天的日期呢?

EN

Stack Overflow用户

发布于 2013-02-10 11:23:08

您应该将Date对象添加到JComboBox中,而不是将当前日期和第二天的日期添加到字符串中,然后使用自定义的ListCellRenderer以所需格式呈现日期。

示例代码:

代码语言:javascript
运行
复制
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 );
    }

}
票数 2
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14793146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档