Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...