8 Replies Latest reply on Jun 22, 2008 3:11 PM by 807589

    Java Calendar Help Needed :)


      I am trying to develop a Java Event Calendar which is able to display the calendar weekly. So the JPanel will be setup with 7 JLists for the days of the week. Buttons will allow switching of the days of the week, months and year.

      Each JList corresponding to the day of the week will have its data obtained from the database using JDBC and loaded upon 're-drawing' of the lists.

      However i am having trouble with the GUI side in understanding how to implement this, i am confident with the JList and database side of things, i have just used a similar example using the Calendar API for monthly displays, however i am unsure how to convert this to a weekly calendar.

      Ideally 7 JLists will always be available in the panel in order M,T,W,T,F,S,S but some will be set to inactive (for example in the first and last weeks of the month).

      If anyone has any suggestions please could you help me out :)
      Sorry if what im trying to do is a bit confusing.

      I've included the code i've been using for the monthly calendar

      public class CalendarPanel extends JPanel implements ActionListener {
        private Calendar panelDate;
        private Label monthLabel;
        private Label yearLabel;
        private Panel daysPanel;
        private Vector calendarListeners;
        private static final String days[] = {"S","M","T","W","T","F","S"};
        public CalendarPanel(){
          super(new BorderLayout());
          panelDate = Calendar.getInstance();
        public CalendarPanel(Calendar date){
          super(new BorderLayout());
          panelDate = (date != null) ? (Calendar)date.clone() : Calendar.getInstance();
        public CalendarPanel(Date date){
          super(new BorderLayout());
          panelDate = Calendar.getInstance();
          if(date != null) panelDate.setTime(date);
        public Calendar getCalendar(){ return panelDate;}
        public void setCalendar(Calendar date){
          if(date != null){
            panelDate = (Calendar)date.clone();
        public void setCalendar(Date date){
          if(date != null){
        public int getYear(){ return panelDate.get(Calendar.YEAR);}
        public String getMonthName(){
          case Calendar.JANUARY: return "January";
          case Calendar.FEBRUARY: return "February";
          case Calendar.MARCH: return "March";
          case Calendar.APRIL: return "April";
          case Calendar.MAY: return "May";
          case Calendar.JUNE: return "June";
          case Calendar.JULY: return "July";
          case Calendar.AUGUST: return "August";
          case Calendar.SEPTEMBER: return "September";
          case Calendar.OCTOBER: return "October";
          case Calendar.NOVEMBER: return "November";
          case Calendar.DECEMBER: return "December";
          case Calendar.UNDECIMBER: return "Undecimber";
          default: return "Unknown";
        private void buildUI(){
          this.add(buildHeaderPanel(), BorderLayout.NORTH);
          daysPanel = new Panel(new GridBagLayout());
          this.add(daysPanel, BorderLayout.CENTER);
        // build the part of the gui that contains the month and year
        // labels with their incrementors / decrementors
        private Panel buildHeaderPanel(){
          monthLabel = new Label(getMonthName(), Label.CENTER);
          yearLabel = new Label(Integer.toString(panelDate.get(Calendar.YEAR)),
          GridBagConstraints gbc = new GridBagConstraints();
          Panel headerPanel = new Panel(new GridBagLayout());
          // month label and buttons
          Panel panel = new Panel(new GridBagLayout());
          Button button = new Button("-");
          button.setActionCommand("decrease month");
          gbc.anchor = GridBagConstraints.EAST;
          panel.add(button, gbc);
          gbc.anchor = GridBagConstraints.CENTER;
          panel.add(monthLabel, gbc);
          button = new Button("+");
          button.setActionCommand("increase month");
          gbc.anchor = GridBagConstraints.WEST;
          panel.add(button, gbc);
          gbc.anchor = GridBagConstraints.CENTER;
          gbc.weightx = 1;
          headerPanel.add(panel, gbc);
          // year label and buttons
          panel = new Panel(new GridBagLayout());
          button = new Button("-");
          button.setActionCommand("decrease year");
          gbc.anchor = GridBagConstraints.EAST;
          gbc.weightx = 0;
          panel.add(button, gbc);
          gbc.anchor = GridBagConstraints.CENTER;
          panel.add(yearLabel, gbc);
          button = new Button("+");
          button.setActionCommand("increase year");
          gbc.anchor = GridBagConstraints.WEST;
          panel.add(button, gbc);
          gbc.anchor = GridBagConstraints.CENTER;
          gbc.weightx = 1;
          headerPanel.add(panel, gbc);
          return headerPanel;
        // redraws the entire panel, including relaying out of
        // the days buttons
        private void redrawPanel(){
          // redraw days panel
          GridBagConstraints gbc = new GridBagConstraints();
          // clear current days panel
          gbc.fill = GridBagConstraints.BOTH;
          gbc.gridx = 0;
          gbc.gridy = 0;
          gbc.weightx = 1;
          gbc.weighty = 1;
          // add days of week
          for(int i = 0; i < days.length; i++, gbc.gridx++)
            daysPanel.add(new Label(days, Label.CENTER), gbc);

      gbc.gridx = 0;

      // days of month
      Button button; // day buttons
      JTable day = new JTable();

      Calendar today = Calendar.getInstance();
      Calendar cellDay = (Calendar)today.clone();
      int month = panelDate.get(Calendar.MONTH);
      int year = panelDate.get(Calendar.YEAR);

      // start with first of panels month
      cellDay.set(year, month, 1);

      gbc.gridx = cellDay.get(Calendar.DAY_OF_WEEK) - 1;

      while( cellDay.get(Calendar.MONTH) == month ){
      if(gbc.gridx > 6){
           gbc.gridx = 0;
      button = new Button(Integer.toString(cellDay.get(Calendar.DATE)));
      if( cellDay.equals(today)){
      daysPanel.add(button, gbc);
      cellDay.add(Calendar.DAY_OF_MONTH, 1);

      // re validate entire panel

      // implementation of ActionListener interface
      // currently no real need to create subclassed action
      // events for calendar. All actions generated by this
      // are action events (generated from the buttons).
      // the action command will be one of the four below
      // or a number (the label of the day button!).

      public void actionPerformed(ActionEvent ae){
      String command = ae.getActionCommand();
      if(command.equals("increase month")){
      panelDate.add(Calendar.MONTH, 1);
      } else if(command.equals("decrease month")){
      panelDate.add(Calendar.MONTH, -1);
      } else if(command.equals("increase year")){
      panelDate.add(Calendar.YEAR, 1);
      } else if(command.equals("decrease year")){
      panelDate.add(Calendar.YEAR, -1);


      // methods for keeping track of interested listeners

      public void addCalendarActionListener(ActionListener al){
      if(al != null){
      if(calendarListeners == null) calendarListeners = new Vector();

      public void removeCalendarActionListener(ActionListener al){
      if((calendarListeners != null) && (al != null)){

      private void notifyCalendarListeners(ActionEvent ae){
      if((calendarListeners != null) && (!calendarListeners.isEmpty())){
      java.util.Enumeration e = calendarListeners.elements();

        • 1. Re: Java Calendar Help Needed :)
          [This is not your own code|http://www.codeguru.com/java/articles/659.shtml].
          • 2. Re: Java Calendar Help Needed :)
            Yeah, i got an example online for a basic calendar selection. I need to modify it though to get weekly displays.

            • 3. Re: Java Calendar Help Needed :)
              DanBarrett2008 wrote:
              Yeah, i got an example online for a basic calendar selection. I need to modify it though to get weekly displays.

              so in other words you took code from online and want us to modify it so it does what you want?
              Where in any of this have you attempted to code it? Why not try and modify it yourself and ask questions if you get into trouble.
              • 4. Re: Java Calendar Help Needed :)
                No i dont want you to modify it, i was just asking about how you can use the Calendar class to show weekly information instead of monthly.

                • 5. Re: Java Calendar Help Needed :)
                  I don't understand the question. What is the "monthly information" you say that program is displaying? Are you referring to the fact that it displays one month at a time?
                  • 6. Re: Java Calendar Help Needed :)
                    Yes, currently it displays the entire month, and the program allows switching between months. What i'm after is the ability to only display weeks of the months. To display only 7 days at a time for the month. With the ability to switch to the next/previous week in the month. A weekly calendar instead of a monthly calendar.

                    • 7. Re: Java Calendar Help Needed :)
                      check your redrawPanel() class and just change a few loops and functions to do only a week instead of the entire month.
                      Everything you need is in that program you just need to trim down what it does
                      • 8. Re: Java Calendar Help Needed :)

                        Sorry for the change of screen name, i'm having trouble with my old account.

                        I have now got most of the system working. However I am having trouble working out how to stop the last days of the previous month appearing in the first week of the next month. For example on 'July 2008' , days 29 and 30 of June are present in the first week of July. How can i get rid of this? And also for the last week of the month, how to get rid of the first days of the next month?

                        import java.awt.BorderLayout;
                        import java.awt.Button;
                        import java.awt.Color;
                        import java.awt.Dimension;
                        import java.awt.GridBagConstraints;
                        import java.awt.GridBagLayout;
                        import java.awt.GridLayout;
                        import java.awt.Label;
                        import java.awt.Panel;
                        import java.awt.event.ActionEvent;
                        import java.awt.event.ActionListener;
                        import java.awt.event.KeyEvent;
                        import java.awt.event.KeyListener;
                        import java.awt.event.MouseAdapter;
                        import java.awt.event.MouseEvent;
                        import java.awt.event.MouseListener;
                        import java.text.SimpleDateFormat;
                        import java.util.Calendar;
                        import java.util.Date;
                        import java.util.Vector;
                        import javax.swing.BorderFactory;
                        import javax.swing.Box;
                        import javax.swing.BoxLayout;
                        import javax.swing.JButton;
                        import javax.swing.JComboBox;
                        import javax.swing.JFrame;
                        import javax.swing.JLabel;
                        import javax.swing.JList;
                        import javax.swing.JPanel;
                        import javax.swing.JPopupMenu;
                        import javax.swing.JScrollPane;
                        import javax.swing.JTextArea;
                        import javax.swing.JTextField;
                        import javax.swing.border.Border;
                        import javax.swing.border.EmptyBorder;
                        import javax.swing.border.EtchedBorder;
                         * @category CalendarSystem
                         * @author Daniel Barrett
                        public class CalendarSystem extends JPanel implements ActionListener, MouseListener, KeyListener   {
                             JPanel events = new JPanel();
                             JPanel action = new JPanel();
                                  //Events Panel
                             DateComboBox eventDateChooser = new DateComboBox();
                             JTextField ref = new JTextField(10);
                             JTextArea eventDetails = new JTextArea();
                             JScrollPane scrollingArea = new JScrollPane(eventDetails);
                             JTextField dateF = new JTextField(15);
                             JTextField timeF = new JTextField(15);
                             String[] minutes = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
                             String[] hours = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
                             JComboBox minsComb = new JComboBox(minutes);
                             JComboBox hourComb = new JComboBox(hours);
                                  //Actions Panel
                             JButton delete = new JButton("Delete");
                             JButton purge = new JButton("Purge");
                             JButton add = new JButton("Add");
                             JButton edit = new JButton("Edit");
                             JButton mview = new JButton("Month View");
                             protected JLabel monthLabel;
                             protected JLabel weekLabel;
                             protected JLabel lmonday = new JLabel("");
                             protected JLabel ltuesday = new JLabel("");
                             protected JLabel lwednesday = new JLabel("");
                             protected JLabel lthursday = new JLabel("");
                             protected JLabel lfriday = new JLabel("");
                             protected JLabel lsaturday = new JLabel("");
                             protected JLabel lsunday = new JLabel("");
                             protected Calendar calendar;
                             protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
                             protected SimpleDateFormat dayFormat = new SimpleDateFormat("MMM"); 
                             JPanel monthCont = new JPanel();
                             JPanel weekCont = new JPanel();
                             JPanel yearCont = new JPanel();
                             JPanel daysOfWeek = new JPanel();
                             JPanel monday = new JPanel();
                             JPanel tuesday = new JPanel();
                             JPanel wednesday = new JPanel();
                             JPanel thursday = new JPanel();
                             JPanel friday = new JPanel();
                             JPanel saturday = new JPanel();
                             JPanel sunday = new JPanel();
                             JList mondayEvents = new JList();
                             JScrollPane mondayEventsScroll = new JScrollPane(mondayEvents);
                             JList tuesdayEvents = new JList();
                             JScrollPane tuesdayEventsScroll = new JScrollPane(tuesdayEvents);
                             JList wednesdayEvents = new JList();
                             JScrollPane wednesdayEventsScroll = new JScrollPane(wednesdayEvents);
                             JList thursdayEvents = new JList();
                             JScrollPane thursdayEventsScroll = new JScrollPane(thursdayEvents);
                             JList fridayEvents = new JList();
                             JScrollPane fridayEventsScroll = new JScrollPane(fridayEvents);
                             JList saturdayEvents = new JList();
                             JScrollPane saturdayEventsScroll = new JScrollPane(saturdayEvents);
                             JList sundayEvents = new JList();
                             JScrollPane sundayEventsScroll = new JScrollPane(sundayEvents);
                             protected Color selectedBackground;
                             protected Color selectedForeground;
                             protected Color background;
                             protected Color foreground;
                             public CalendarSystem(){
                                  this.calendar = Calendar.getInstance();
                                  this.setLayout(new BoxLayout(this,1));
                                  this.setMaximumSize(new Dimension(400,30));
                             private void setupActions() {
                             private void setupEvents() {
                                  this.events.setBorder(BorderFactory.createTitledBorder("Event Details"));
                                  this.events.setLayout(new BoxLayout(this.events,1));
                                  JPanel row1 = new JPanel();
                                  JPanel row2 = new JPanel();
                                  JPanel row3 = new JPanel();
                                  JLabel la = new JLabel("Reference");
                                  JLabel da = new JLabel("Date");
                                  JLabel time = new JLabel("Time");
                                  JLabel det = new JLabel("Details");
                                  scrollingArea.setPreferredSize(new Dimension(600,50));
                             protected JLabel createUpdateButton(final int field, final int amount, final boolean month) {
                                 final JLabel label = new JLabel();
                                 final Border selectedBorder = new EtchedBorder();
                                 final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
                                 label.addMouseListener(new MouseAdapter() {
                                      public void mouseReleased(MouseEvent e) {
                                       calendar.add(field, amount);
                                       public void mouseEntered(MouseEvent e) {
                                      public void mouseExited(MouseEvent e) {
                                 return label;
                             private void updateMCalendar() {
                                  this.calendar.set(Calendar.DAY_OF_MONTH, 1);
                             private void setupHeaders() {
                                  //MONTH CONTROLS
                                 monthCont.setLayout(new BoxLayout(monthCont, BoxLayout.X_AXIS));
                                 JLabel label;
                                 label = createUpdateButton(Calendar.YEAR, -1,false);
                                 label.setToolTipText("Previous Year");
                                 label = createUpdateButton(Calendar.MONTH, -1,true);
                                 label.setText("< "); 
                                 label.setToolTipText("Previous Month");
                                 monthLabel =new JLabel("", JLabel.CENTER);
                                 label =createUpdateButton(Calendar.MONTH, 1,true);
                                 label.setText(" >");
                                 label.setToolTipText("Next Month");
                                 label = createUpdateButton(Calendar.YEAR, 1,false);
                                 label.setToolTipText("Next Year");
                                 //WEEK CONTROLS
                                 weekCont.setLayout(new BoxLayout(weekCont, BoxLayout.X_AXIS));
                                 JLabel label1;
                                 label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, -1,false);
                                 label1.setToolTipText("Previous Week");
                                 weekLabel =new JLabel("", JLabel.CENTER);
                                 JLabel lweek =new JLabel("Week:  ", JLabel.CENTER);
                                 label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, 1,false);
                                 label1.setToolTipText("Next Week");
                             public void setupDays(){
                                  monday.setLayout(new BoxLayout(monday,1));
                                  tuesday.setLayout(new BoxLayout(tuesday,1));
                                  wednesday.setLayout(new BoxLayout(wednesday,1));
                                  thursday.setLayout(new BoxLayout(thursday,1));
                                  friday.setLayout(new BoxLayout(friday,1));
                                  saturday.setLayout(new BoxLayout(saturday,1));
                                  sunday.setLayout(new BoxLayout(sunday,1));
                                  this.mondayEventsScroll.setPreferredSize(new Dimension(90,200));
                                  this.monday.setPreferredSize(new Dimension(145,300));
                                  this.tuesdayEventsScroll.setPreferredSize(new Dimension(90,200));
                                  this.tuesday.setPreferredSize(new Dimension(145,300));
                                  this.wednesdayEventsScroll.setPreferredSize(new Dimension(90,200));
                                  this.wednesday.setPreferredSize(new Dimension(145,300));
                                  this.thursdayEventsScroll.setPreferredSize(new Dimension(90,200));
                                  this.thursday.setPreferredSize(new Dimension(145,300));
                                  this.fridayEventsScroll.setPreferredSize(new Dimension(90,200));
                                  this.friday.setPreferredSize(new Dimension(145,300));
                                  this.saturdayEventsScroll.setPreferredSize(new Dimension(90,200));
                                  this.saturday.setPreferredSize(new Dimension(145,300));
                                  this.sundayEventsScroll.setPreferredSize(new Dimension(90,200));
                                  this.sunday.setPreferredSize(new Dimension(145,300));
                            private void updateCalendar() {
                                 monthLabel.setText(monthFormat.format(calendar.getTime()) );
                                 //Blank out / empty strings for first elements that do not start on sunday
                                 Calendar setupCalendar = (Calendar) calendar.clone();
                                 setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
                               // while(setupCalendar.get(Calendar.DAY_OF_WEEK) < calendar.getActualMaximum(Calendar.DAY_OF_WEEK)) {
                                    //System.out.println("day of month: " + setupCalendar.get(Calendar.DAY_OF_MONTH));
                                    //System.out.println("day of week: " + (setupCalendar.get(Calendar.DAY_OF_WEEK)));
                                    //System.out.println("week of month: " + calendar.get(Calendar.WEEK_OF_MONTH) + "\n");
                                    setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                                    setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                                    setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                                    setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                                    setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                                    setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                            public void setDayLabels(int day, int dayOfWeek){
                                 if(dayOfWeek == 1){
                                 if(dayOfWeek == 2){
                                 if(dayOfWeek == 3){
                                 if(dayOfWeek == 4){
                                 if(dayOfWeek == 5){
                                 if(dayOfWeek == 6){
                                 if(dayOfWeek == 7){
                             public void actionPerformed(ActionEvent arg0) {
                             public void mouseClicked(MouseEvent arg0) {
                                  // TODO Auto-generated method stub
                             public void mouseEntered(MouseEvent arg0) {
                                  // TODO Auto-generated method stub
                             public void mouseExited(MouseEvent arg0) {
                                  // TODO Auto-generated method stub
                             public void mousePressed(MouseEvent arg0) {
                                  // TODO Auto-generated method stub
                             public void mouseReleased(MouseEvent arg0) {
                                  // TODO Auto-generated method stub
                             public void keyPressed(KeyEvent arg0) {
                                  // TODO Auto-generated method stub
                             public void keyReleased(KeyEvent arg0) {
                                  // TODO Auto-generated method stub
                             public void keyTyped(KeyEvent arg0) {
                                  // TODO Auto-generated method stub
                             public static void main(String args[]){
                                  JFrame frame = new JFrame();
                                  frame.setSize(1100, 670);
                                  frame.add(new CalendarSystem());