javacalendarjcalendar

How to get selected item on Jcalendar


I load my jCalendar to Calendar then I used the day for the index but problem every month's days different so I can't select. When I click 21, I'm selecting 10.

   Calendar cal = Calendar.getInstance();

   cal.setTime(jCalendar1.getDate());
   int day = cal.get(Calendar.DAY_OF_MONTH);

   JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
   Component compo[] = jpanel.getComponents();
   compo[day].setBackground(Color.red);

Solution

  • public class CalendarTest2 extends JFrame {
        private static final long serialVersionUID = 1L;
    
        public CalendarTest2() {
            Calendar cal = Calendar.getInstance();
            JCalendar jCalendar1 = new JCalendar();
            cal.setTime(jCalendar1.getDate());
            int dayToBeSelected = cal.get(Calendar.DAY_OF_MONTH);
            dayToBeSelected = 21;
    
            JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
            Component compo[] = jpanel.getComponents();
            for (Component comp : compo) {
                if (!(comp instanceof JButton))
                    continue;
    
                JButton btn = (JButton) comp;
                if (btn.getText().equals(String.valueOf(dayToBeSelected)))
                    comp.setBackground(Color.red);
            }
            add(jpanel);
        }
    
        public static void main(String[] args) {
            CalendarTest2 test = new CalendarTest2();
            test.setVisible(true);
            test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            test.setSize(800, 800);
        }
    }
    

    Instead of accessing the 'button to be selected' through index, try to access the button through the text(day number) written on it. The reason is, calendar of a month is displayed using 49 buttons arranged in 7x7 fashion as shown. So for ex) index 0 will always point to 'Sunday' button.