1

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

Catalina Island
  • 7,027
  • 2
  • 23
  • 42
Cruz
  • 13
  • 3
  • 1
    I recommend you don’t use `Calendar`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Best if you can find a calendar UI component that supports java.time, they exist. Otherwise convert. – Ole V.V. May 03 '22 at 07:54
  • 1
    In either calendar, use named constants. Why not use `JMonthChooser` and `JYearChooser` side-by-side, maybe with a common listener? – Catalina Island May 17 '22 at 15:57

1 Answers1

1

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

trashgod
  • 203,806
  • 29
  • 246
  • 1,045