简体   繁体   中英

JCalendar sets to March 30 when February is chosen

Code consists of just month and year can be chosen in , by default the day is 30 and 28 for February, the issue comes when I choose February, automatically sets to March 30; this is the code; it is in PropertyChange event of .

Calendar cal = PFI.getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if(month==1){
    cal.set(year, 1 , 28);
    PFI.setCalendar(cal);
}
else
{
    cal.set(year, month , 30);
    PFI.setCalendar(cal);
}

Combining the suggestions of @Ole VV and @Catalina Island , the fragment below illustrates JYearChooser and JMonthChooser in a GridLayout . A common listener then uses java.time to display the last day of the selected year and month.

年月图片


JPanel panel = new JPanel(new GridLayout(1, 0));
JMonthChooser jmc = new JMonthChooser();
JYearChooser jyc = new JYearChooser();
JLabel label = new JLabel("Last day of month:");
label.setHorizontalAlignment(JLabel.RIGHT);
JTextField last = new JTextField(8);
label.setLabelFor(last);
PropertyChangeListener myListener = new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent e) {
        LocalDate ld = LocalDate.of(jyc.getYear(), jmc.getMonth() + 1, 1)
            .with(TemporalAdjusters.lastDayOfMonth());
        last.setText(ld.format(DateTimeFormatter.ISO_DATE));
    }
};
myListener.propertyChange(null);
jmc.addPropertyChangeListener("month", myListener);
jyc.addPropertyChangeListener("year", myListener);
panel.add(jyc);
panel.add(jmc);
panel.add(label);
panel.add(last);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM