如何根据月份和年份填充天组合框?
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;
}
我在学校里有一个重要的Java Swing程序需要帮助.
I need some help with a Java Swing program I have for school which is important.
如何根据月份和年份(包括leap年)填写天数?我使用了3个单独的组合框,一个组合用于几天,另一个组合用于几个月,另一个组合用于多年.还应该从方法中调用它.
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.
最佳"解决方案是利用可用功能.
The "best" solution is take advantage of the available functionality.
Java 8+引入了java.time
API,它取代了基于Calendar
和Date
的API
Java 8+ introduced the java.time
API, which replaces the Calendar
and Date
based APIs
例如,使用 YearMonth
类…
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());
}
将打印...
2010 = 28
2011 = 28
2012 = 29
2013 = 28
2014 = 28
2015 = 28
2016 = 29
2017 = 28
2018 = 28
2019 = 28
2020 = 29
由此,您可以简单地创建一个新的ComboBoxModel
,用所需的值填充并将其应用于JComboBox
的实例-请参见
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.