Tagged: canvas Toggle Comment Threads | Keyboard Shortcuts

  • pit 3:09 pm on September 15, 2008 Permalink | Reply
    Tags: canvas, , , menu, menu transition, sliding menu,   

    Building a J2ME sliding menu with text and images 

    Whatever you’re building, a game or an application, you always need a menu to let users navigate through sections of your MIDlet.

    This article will show how to build a menu with text and icons, and with a nice sliding effect to go from one menu item to another. You can see the final effect on the emulator page: J2ME Sliding Menu in action.

    Source code: SlideIconsMenu class

    As always, let’s start defining our class:

    public class SlideIconsMenu

    Now, we define some appearance-related properties, that can be customized to change menu colors and font.

    // selected item index
    public int selectedIndex = 0;
    // icon label color
    public int textColor = 0xff0000;
    // menu bg color
    public int bgColor = 0xffffff;
    // icon label font
    public Font textFont = Font.getDefaultFont();
    // menu right and left Images
    public Image slideRightImage = null;
    public Image slideLeftImage = null;

    And some other properties, that will be internally used by the menu class itself, to handle content and the sliding animation:

    // menu size
    int width = 0;
    int height = 0;
    // item labels
    String[] labels = null;
    // item icons
    Image[] icons = null;
    // previous item index (during menu translation)
    int prevIndex = 0;
    // menu sliding translation properties
    public int translationDuration = 500;
    long startTranslationTime = 0;

    Now, let’s define the menu constructor. We need a constructor that will accept these arguments:

    • a set of item labels
    • a set of images, one for each item
    • the menu width
    • and the menu height
    public SlideIconsMenu(String[] labels, Image[] icons, int width, int height) throws Exception
    	this.width = width;
    	this.height = height;
    	this.labels = labels;
    	this.icons = icons;
    	slideRightImage = Image.createImage("/slide_right.png");
    	slideLeftImage = Image.createImage("/slide_left.png");

    The constructor also creates 2 Images to represent the left and right sliding arrows, that will be used to indicate more items on the menu left/right side. So, in your code, you must adapt those image paths to match existing ones within your project.

    Now we must handle item change, by letting our menu slide with a nice transition. To do this, we’ll manage the item change with the following slideItem() method:

    public void slideItem(int delta)
    	if(!isTranslating() && selectedIndex + delta >= 0 && selectedIndex + delta < labels.length)
    		prevIndex = selectedIndex;
    		selectedIndex += delta;
    		startTranslationTime = System.currentTimeMillis();
    public boolean isTranslating()
    	return prevIndex != selectedIndex;

    And finally, since we need to paint our menu, here is its paint() method:

    public void paint(Graphics g)
    	g.fillRect(0, 0, width, height);
    	if(selectedIndex > 0)
    		g.drawImage(slideLeftImage, 2, height / 2, Graphics.LEFT | Graphics.VCENTER);
    	if(selectedIndex < icons.length - 1)
    		g.drawImage(slideRightImage, width - 2, height / 2, Graphics.RIGHT | Graphics.VCENTER);
    	g.drawString(labels[selectedIndex], width / 2, height - 2, Graphics.BOTTOM | Graphics.HCENTER);
    	g.setClip(slideLeftImage.getWidth(), 0, width - 2 * slideLeftImage.getWidth(), height);
    	if(selectedIndex != prevIndex)
    		int diff = (int)(System.currentTimeMillis() - startTranslationTime);
    		if(diff > translationDuration)
    			diff = translationDuration;
    		int coeff = selectedIndex > prevIndex ? 1 : - 1;
    		int currentX = width / 2 - coeff * diff * width / translationDuration;
    		int nextX = currentX + width * coeff;
    		g.drawImage(icons[prevIndex], currentX, height / 2, Graphics.VCENTER | Graphics.HCENTER);
    		g.drawImage(icons[selectedIndex], nextX, height / 2, Graphics.VCENTER | Graphics.HCENTER);
    		if(diff >= translationDuration)
    			prevIndex = selectedIndex;
    		g.drawImage(icons[selectedIndex], width / 2, height / 2, Graphics.VCENTER | Graphics.HCENTER);

    Sample usage

    Here’s a sample Canvas that uses the SlideIconsMenu class. The main steps are:

    • the menu constructions
    • the key handling, done within the Canvas keyPressed() method
    • the menu repainting, done periodically, to allow the sliding transition to be smoothly drawn
    import javax.microedition.lcdui.Canvas;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    public class SlideIconsCanvas extends Canvas implements Runnable
    	SlideIconsMenu menu = null;
    	public SlideIconsCanvas()
    		Image[] im = new Image[3]; 
    			im[0] = Image.createImage("/item0.png");
    			im[1] = Image.createImage("/item1.png");
    			im[2] = Image.createImage("/item2.png");
    			menu = new SlideIconsMenu(
    				new String[]{"Item 1", "Item 2", "Item 3"},
    			new Thread(this).start();
    		catch(Exception e)
    	protected void paint(Graphics g)
    	public void keyPressed(int key)
    		int gameKey = getGameAction(key);
    		if(gameKey == Canvas.RIGHT)
    		else if(gameKey == Canvas.LEFT)
    			menu.slideItem(- 1);
    	public void run()
    		catch(Exception e)

    Download source code

    You can download full source code here:

    • deanet 7:21 pm on September 24, 2008 Permalink

      wew … nice code :mrgreen:

    • Stella 8:26 am on October 1, 2008 Permalink

      Hi ,
      this screen is brilliant, i was wondering if you could come up with a design that is similar to the carousel interface of yahoo GO!. this design is quite close to that

      byeeeee ;)

    • pit 9:04 am on October 1, 2008 Permalink

      Thanks for your feedback :)

      @stella: check out this other article, if it could suit your needs

    • Stella 7:04 am on October 15, 2008 Permalink

      yep i seen that. but that uses JSR226 right :( what about devices that dont have JSR266


    • Tyler 1:22 pm on April 30, 2009 Permalink

      Hi jappit;
      i have look at your code but i think you always refresh screen and wait 100ms. right? It uses 100% processor.

    • jermaine 3:23 am on September 29, 2010 Permalink

      thanks for this bit of code…but uhm, how do i run this? i copied the source codes but i dont know where to place the jar files…

  • pit 8:44 am on September 12, 2008 Permalink | Reply
    Tags: canvas, , , , list, ,   

    How to build a Canvas based List in J2ME 

    Quite a bit of time is passed since the last Java ME tutorial.. so It’s time for something new, don’t you think?

    Today we’ll see how it is possible to implement a simple Canvas based List, with the following features:

    • customizable style (colors, margins, font)
    • vertical scrolling
    • image and text support (as for standard Java ME Lists)

    Java ME Canvas based List screenshot

    It is possible to see this code in action on the emulator page.

    Writing the code

    First thing you should define some style-related properties, that will be used to paint the List items. Name of single properties is self-explaining.

    int linePadding = 2;
    int margin = 2;
    int padding = 2;
    Font font = Font.getDefaultFont();
    int bgColor = 0xffffff;
    int foreColor = 0x000000;
    int foreSelectedColor = 0xffffff;
    int backColor = 0xffffff;
    int backSelectedColor = 0x0000ff;
    int borderWidth = 3;
    int borderColor = 0x000000;
    int borderSelectedColor = 0xff0000;

    Now, here are some internal properties, that will be used to handle list items content and positioning.

    // will contain item splitted lines
    String[][] itemLines = null;
    // will hold items image parts
    Image[] images = null;
    // will hold selected item index
    public int selectedItem = 0;
    // these will hold item graphical properties
    int[] itemsTop = null;
    int[] itemsHeight = null;
    // these will hold List vertical scrolling
    int scrollTop = 0;
    final int SCROLL_STEP = 40;

    Now, here is the CanvasList constructor. Its arguments are (similarly to javax.microedition.lcdui.List constructor):

    • the screen’s title
    • set of strings specifying the string parts of the List elements
    • set of images specifying the image parts of the List elements

    This article will not cover the handling of different types of Lists (e.g.: exclusive, multiple, ..).

    public CanvasList(String title, String[] items, Image[] imageElements)
    	this.images = imageElements;
    	itemLines = new String[items.length][];
    	itemsTop = new int[itemLines.length];
    	itemsHeight = new int[itemLines.length];
    	for(int i = 0; i < itemLines.length; i++)
    		// get image part of this item, if available
    		Image imagePart = getImage(i);
    		// get avaiable width for text
    		int w = getItemWidth() - (imagePart != null ? imagePart.getWidth() + padding : 0);
    		// and split item text into text rows, to fit available width
    		itemLines[i] = getTextRows((String) items[i], font, w);

    Here are the 2 utility methods found in the CanvasList constructor:

    public int getItemWidth()
    	return getWidth() - 2 * borderWidth - 2 * padding - 2 * margin;
    Image getImage(int index)
    	return images != null && images.length > index ? images[index] : null;

    Now, here is the paint() method:

    protected void paint(Graphics g)
    	// paint List background
    	g.fillRect(0, 0, getWidth(), getHeight());
    	// translate accordingly to current List vertical scroll
    	g.translate(0, - scrollTop);
    	int top = 0;
    	// loop List items
    	for(int i = 0; i < itemLines.length; i++)
    		int itemRows = itemLines[i].length;
    		Image imagePart = getImage(i);
    		int itemHeight = itemRows * font.getHeight() + linePadding * (itemRows - 1);
    		itemsTop[i] = top;
    		itemsHeight[i] = itemHeight;
    		// is image part higher than the text part?
    		if(imagePart != null && imagePart.getHeight() > itemHeight)
    			itemHeight = imagePart.getHeight();
    		itemHeight += 2 * padding + 2 * borderWidth;
    		g.translate(0, top);
    		if(borderWidth > 0)
    			// paint item border
    			g.setColor(i == selectedItem ? borderSelectedColor : borderColor);
    			g.fillRect(margin, margin, getWidth() - 2 * margin, itemHeight);
    		// paint item background
    		g.setColor(i == selectedItem ? backSelectedColor : backColor);
    		g.fillRect(margin + borderWidth, margin + borderWidth, getWidth() - 2 * margin - 2 * borderWidth, itemHeight - 2 * borderWidth);
    		// has this item an image part?
    		if(imagePart != null)
    			g.drawImage(imagePart, margin + borderWidth + padding, margin + borderWidth + padding, Graphics.TOP | Graphics.LEFT);
    		// paint item text rows
    		g.setColor(i == selectedItem ? foreSelectedColor : foreColor);
    		int textLeft = margin + borderWidth + padding + (imagePart != null ? imagePart.getWidth() + padding : 0);
    		for(int j = 0; j < itemRows; j++)
    			g.drawString(itemLines[i][j], textLeft, margin + borderWidth + padding + j * (linePadding + font.getHeight()), Graphics.TOP | Graphics.LEFT);
    		g.translate(0, - top);
    		top += itemHeight + 2 * margin;
    	// finally, translate back
    	g.translate(0, scrollTop);

    And finally, to handle user key events, here is the keyPressed() event:

    protected void keyPressed(int key)
    	int keyCode = getGameAction(key);
    	// is there 1 item at least?
    	if(itemLines.length > 0)
    		// going up
    		if(keyCode == Canvas.UP)
    			// current item is clipped on top, so can scroll up
    			if(itemsTop[selectedItem] < scrollTop)
    				scrollTop -= SCROLL_STEP;
    			// is there a previous item?
    			else if(selectedItem > 0)
    		//going down
    		else if(keyCode == Canvas.DOWN)
    			// current item is clipped on bottom, so can scroll down
    			if(itemsTop[selectedItem] + itemsHeight[selectedItem] >= scrollTop + getHeight())
    				scrollTop += SCROLL_STEP;
    			// is there a following item?
    			else if(selectedItem < itemLines.length - 1)

    About the getTextRows() method, you can grab an implementation (but you could find a lot of other ones on the Web) on this other article written some time ago: J2ME Scrollable Text.

    How to use CanvasList class

    Here is a sample usage of CanvasList class, that will display a list (without image parts):

    String[] items = new String[]{"Item 1", "Item 2", "Item 3"};
    CanvasList myCanvas = new CanvasList("Test canvas", items, null);

    To add images to your items, it’s necessary to instantiate an Image array, and pass it to CanvasList constructor as its third argument:

    Image[] images = null;
    	images = new Image[]{
    catch(Exception e)
    String[] items = new String[]{"Item 1", "Item 2", "Item 3"};
    CanvasList myCanvas = new CanvasList("Test canvas", items, images);

    Related resources

    You can download full CanvasList source code here: CanvasList.java

    • cool8jay 9:19 am on June 24, 2010 Permalink

      Very good tutorial about scrollable list view, it meets my demand. But the getTextRows() method has some shortcoming: it does not support language not using space as delimiter, like Chinese and Japanese.

      Here is a more flexible version:

    • ketut joko 2:04 pm on July 7, 2011 Permalink

      when i add this file class my main class cant detect, can u explain it please?

    • pooja 12:48 pm on January 16, 2013 Permalink

      Thanks. Nice post.

      But I am phasing the problem in converting the same for touch. As we need to give touch scrolling on the list. This post is for keypress events. can you please provide the same with touch scrolling.

  • pit 1:39 pm on June 23, 2008 Permalink | Reply
    Tags: canvas, , , sliding animations,   

    How to add sliding transitions between Canvas in J2ME 

    Today we’ll see a simple way to add sliding transition between Canvas in a Java ME application. Just take a look at it in the emulator page to see how it performs: Canvas sliding transitions in action!

    j2me canvas sliding transition screenshot

    The source code


    First of all, we know that Canvas paint() method is protected, so, to access it from the class we’ll build, we must extend its visibility by extending Canvas class itself. We’ll do it by defining our FxBaseClass in this simple way:

    import javax.microedition.lcdui.Canvas;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Canvas;
    import javax.microedition.lcdui.Graphics;
    public class FxBaseCanvas extends Canvas
    	public void paint(Graphics g)


    Now, we start building our CanvasSlideFx class, that will extend Canvas itself. We start defining some useful properties:

    // time related properties
    long startTime = 0;
    long duration = 0;
    // current state of the transition
    boolean running = false;
    // direction of sliding
    int direction = LEFT;
    // the previous and next Canvas instances
    FxBaseCanvas fromCanvas = null;
    FxBaseCanvas toCanvas = null;
    // the current Display object
    Display display = null;
    // properties used to correctly place the 2 Canvas
    int deltaX = 0;
    int deltaY = 0;

    Now, we define our class constructor, that will initialize coordinate properties according to the specified transition direction. The detailed argument list is:

    • The current Display object, that will be used to retrieve the current displayed Canvas, and to set the next one
    • The destination Canvas, that will extend the previously defined FxBaseCanvas class
    • The transition direction (one of Canvas.UP, RIGHT, DOWN or LEFT)
    • The transition duration, in milliseconds
    public CanvasSlideFx(Display display, FxBaseCanvas toCanvas, int direction, long duration)
    	this.display = display;
    	this.fromCanvas = (FxBaseCanvas)display.getCurrent();
    	this.toCanvas = toCanvas;
    	this.direction = direction;
    	this.duration = duration;
    	case UP:
    		deltaY = - getHeight(); break;
    	case RIGHT:
    		deltaX = getWidth(); break;
    	case DOWN:
    		deltaY = getHeight(); break;
    	case LEFT:
    		deltaX = - getWidth(); break;

    Now, we define a startTransition() method, that will actually start the animation. To implement the animation itself, we let our class implement Runnable.

    void startTransition()
    	this.startTime = System.currentTimeMillis();
    	running = true;
    	new Thread(this).start();

    And here’s the run() method implementation, that we must implement from Runnable interface. As long as the animation is running, we will repaint our animated Canvas, with a given interval of 50 milliseconds (but you can freely change this). When it finishes (so, running is false), we will exit the main loop and set the current Displayable to our toCanvas.

    public void run()
    	catch(Exception e)

    Finally, we have our paint() method, that will actually paint our transition. It will do this by painting both the source and the destination Canvas, translating them according to the transition direction, and to the elapsed time.

    protected void paint(Graphics g)
    	long diff = System.currentTimeMillis() - startTime;
    	if(diff >= duration)
    		running = false;
    		diff = duration;
    	int perc = (int)(100 * diff / duration);
    	int dx = deltaX * perc / 100;
    	int dy = deltaY * perc / 100;
    	g.translate(dx, dy);
    	g.translate(- deltaX, - deltaY);
    	g.translate(deltaX - dx, deltaY - dy);

    How to use it?

    Now we’ll see how to integrate the CanvasSlideFx within an existing code that already uses Canvas.
    So, let’s assume that our application currently has, somewhere in its code, these lines:

    MyCanvas firstCanvas = new MyCanvas();
    //and somewhere else
    MyOtherCanvas secondCanvas = new MyOtherCanvas();

    where MyCanvas and MyOtherCanvas will likely extend Canvas.

    Now here are the required steps to integrate transitions in our code:

    1. First of all, we must make MyCanvas and MyOtherCanvas extend FxBaseCanvas instead of directly Canvas. So, we’ll have:
      public class MyCanvas extend FxBaseCanvas ...
    2. Then, let’s say we want to animate the transition between firstCanvas and secondCanvas, we will remove the code:

      and replace it with:

      CanvasSlideFx fxCanvas = new CanvasSlideFx(
    3. and we’ve done it! :)

    Resources and download

    You can download the code explained in this article with the following links:

  • pit 4:06 pm on May 16, 2008 Permalink | Reply
    Tags: , canvas, date field, date item, date picker, ,   

    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.

    • rachelwiz 1:19 pm on September 23, 2009 Permalink


      I created a midlet program and tried to compile this Calendar picker application, it gave me the following errors –

      C:\WTK23\apps\CalendarMidlet\src\CalendarWidget.java:79: cannot find symbol
      symbol : method ceil(double)
      location: class java.lang.Math
      this.weeks = (int)Math.ceil(((double)getStartWeekday() + getMonthDays()) / 7);
      C:\WTK23\apps\CalendarMidlet\src\CalendarWidget.java:79: inconvertible types
      found : java.lang.Math.ceil
      required: int
      this.weeks = (int)Math.ceil(((double)getStartWeekday() + getMonthDays()) / 7);
      2 errors
      Build failed

      I also added “import java.lang.Math;” this line in my code but still its throwing the same error.

      what may be the problem? Can you please help me in this.

    • Manolo 7:47 am on January 15, 2010 Permalink

      Can i do that on Android, anyone can share some codes.

    • raj 8:28 am on October 14, 2010 Permalink

      than q. this is very use full

    • panthibo 9:05 pm on April 24, 2011 Permalink

      If you have errors with Math.ceil, try this:
      this.weeks = (int)Math.ceil(((double)getStartWeekday() + getMonthDays()) / 7);
      this.weeks = (int)(0.9 + ((double)getStartWeekday() + getMonthDays()) / 7);

      It’s working

    • Rajesh 2:40 pm on May 24, 2011 Permalink

      The Above Appllication runs fine in midlet but when we creat a JAD File it throws Exception
      Try This using JAD File

  • pit 11:13 am on April 22, 2008 Permalink | Reply
    Tags: canvas, , table   

    J2ME Table component with focus and scroll 

    Sometimes it happens that you must draw a table within a J2ME application. Even if there are some nice UI frameworks out there, they’re simply oversized if you need only a simple, plain, scrollable table.

    This is the reason why I’ve decided to write a custom component that you can use to draw tables, with the following features:

    • Focusable cells
    • Vertical scrolling
    • Auto-sizing columns

    J2ME canvas table screenshot

    Some nice features to be added in a future version could be, for example:

    • Cell wrap when moving from a cell to another
    • Horizontal scrolling, to support tables with a lot of columns
    • Support for headers

    You can see a live version on the emulator page. Full midlet source code is available here.

    • Ardian Eko 7:24 pm on May 15, 2008 Permalink

      thanks, I’ll try it first.


    • bnm 5:19 am on May 27, 2008 Permalink

      kuull.. thx :)

    • Elton kent 8:12 am on June 27, 2008 Permalink

      why doesnt it scroll horizontally when more that 4 rows are added. the netbeans TableItem does

    • Shiva 9:16 am on June 1, 2009 Permalink

      Hi, I’m new in j2me, is there any way to add table header to it?

    • Hu Rui 3:08 pm on October 8, 2009 Permalink

      Thanks for your source code. It make me save lots of time to redesgine a new datagrid.

    • Baldo Bodi 1:16 pm on November 25, 2009 Permalink

      I’m trying to import data from a tiny editor to an mobile apply, and for the table problem I recurr to this code.


      But I’ve the problem for more width table don’t can scroll horizontally.

      If anyone have a solution, I will be very pleased to hear how do it.

    • Asif javed 8:21 pm on April 3, 2010 Permalink

      how can i get the source code.

    • Future Gadgets 9:42 am on February 23, 2011 Permalink

    • Ajay 7:18 am on April 14, 2011 Permalink

      when i installing jar file in my nokia 6300 and N-95 the application show a error “Application is not supported at this phone”,what i do in this stitutaion…anybody can hepl me..

compose new post
next post/next comment
previous post/previous comment
show/hide comments
go to top
go to login
show/hide help
shift + esc