Reputation: 31
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.
Upvotes: 0
Views: 1838
Reputation: 347332
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.
Upvotes: 4