Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

java - How to populate days combobox based on month and year?

private void buildMonthsList(cmbMonth monthsList) {
    for (int monthCount = 0; monthCount < 12; monthCount++)
        monthsList.addItem(Const.MONTHS[monthCount]);
}

public boolean DaysComboBox (int year)
{
    Calendar cal = Calendar.getInstance();
    int months = cal.get(Calendar.MONTH);

    year = (int) cmbYear.getSelectedItem();
    boolean leap = false;

    if(year % 4 == 0)
    {
        if( year % 100 == 0)
        {
            // year is divisible by 400, hence the year is a leap year
            if ( year % 400 == 0)
            {
                leap = true;
            }
            else {
                leap = false;
            }
        }
        else {
            leap = true;
        }
    }
    else {
        leap = false;
    }

    return leap;
}

I need some help with a Java Swing program I have for school which is important.

How can you fill in the number of days according to the month and year including leap year? I used 3 separate combo boxes, one for the days, another one for the months and another for the years. It should also be called from a method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The "best" solution is take advantage of the available functionality.

Java 8+ introduced the java.time API, which replaces the Calendar and Date based APIs

For example, something like this, using YearMonth class…

for (int year = 2010; year <= 2020; year++) {
    YearMonth ym = YearMonth.of(year, Month.FEBRUARY);
    System.out.println(year + " = " + ym.lengthOfMonth());
}

will print...

2010 = 28
2011 = 28
2012 = 29
2013 = 28
2014 = 28
2015 = 28
2016 = 29
2017 = 28
2018 = 28
2019 = 28
2020 = 29

From this, you can simply create a new ComboBoxModel, fill it with the values you need and apply it to the instance of JComboBox - see How to Use Combo Boxes for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...