A J2ME Calendar for all your Canvas!

You know that J2ME support for Canvas is quite ridiculous.. One list, some form items, and stop. Canvas is left to its terrible destiny, with nothing more than a couple of lines and circles.. isn’t it sad?
So, after this melodramatic introduction, we’re ready for today’s code: a fully featured, customizable, Canvas based calendar!

J2me Canvas Date Picker screenshot

If you prefer a live demonstration rather than a simple screenshot, just go here: Canvas Calendar in action.

So, how to use it?

  1. Download its source code (CalendarWidget.java) and put it straight in your project
  2. Instantiate it within your Canvas with its plain-old-unique constructor:
    CalendarWidget calendar = new CalendarWidget(new Date());
  3. Customize it with the colors/fonts/padding you prefer:
    calendar.headerFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE);
    calendar.weekdayFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
    calendar.weekdayBgColor = 0xccccff;
    calendar.weekdayColor = 0x0000ff;
    calendar.headerColor = 0xffffff;
  4. After you’ve customized it, remember to always call its initialize() method:
  5. Now, to paint it, you can simply call its paint() method from your Canvas paint(), like this:
    protected void paint(Graphics g)
        g.fillRect(0, 0, getWidth(), getHeight());
  6. Now you must allow users to interact with it, so you can, for example, use Canvas keyPressed() method to interact with calendar:
    protected void keyPressed(int key)
        int keyCode = getGameAction(key);
        if(keyCode == FIRE)
                new Alert("Selected date", calendar.getSelectedDate().toString(), null, AlertType.CONFIRMATION)

    As you see, what we do is this:

    • if the user press FIRE button, we alert the current selected date
    • otherwise we call calendar keyPressed() method, to make it behave accordingly
  7. Other customizable properties include:
    • MONTH_LABELS: change this to customize month labels in your own language
    • WEEKDAY_LABELS: as above, change this to customize weekday labels
    • startWeekday: this represents the week starting day, and its values range goes from 0 (for Monday) to 6 (for Sunday)

You can download source code of the example described above here: CalendarCanvas.java.

To get some more details about CalendarWidget source code, you can take a look at my article on Forum Nokia Wiki: Building a J2ME Canvas based Calendar / Date picker.

Be Sociable, Share!