JCalendar sets to March 30 when February is chosen

62 views Asked by At

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);
}

1

There are 1 answers

0
trashgod On

Combining the suggestions of @Ole V.V. 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.

year month image


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);