Tagged: source code Toggle Comment Threads | Keyboard Shortcuts

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

    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)
    {
    	setTitle(title);
     
    	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.setColor(bgColor);
    	g.fillRect(0, 0, getWidth(), getHeight());
     
    	// translate accordingly to current List vertical scroll
    	g.translate(0, - scrollTop);
     
    	int top = 0;
     
    	g.setFont(font);
     
    	// 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;
     
    				repaint();
    			}
    			// is there a previous item?
    			else if(selectedItem > 0)
    			{
    				selectedItem--;
     
    				repaint();
    			}
    		}
    		//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;
     
    				repaint();
    			}
    			// is there a following item?
    			else if(selectedItem < itemLines.length - 1)
    			{
    				selectedItem++;
     
    				repaint();
    			}
    		}
    	}
    }

    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;
    try
    {
    	images = new Image[]{
    		Image.createImage("/item1.png"),
    		Image.createImage("/item2.png"),
    		Image.createImage("/item3.png")
    	};
    }
    catch(Exception e)
    {
    	e.printStackTrace();
    }
    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:
      http://dev.firnow.com/course/3_program/java/javajs/20090304/157622.html#comment

    • 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 10:26 am on May 20, 2008 Permalink | Reply
    Tags: effect, explode, , , , source code,   

    Let your images explode in J2ME! 

    After a MIDP 1.0 utility to rotate images now time has come for some image fun :)

    J2ME Image explode effect screenshot
    When writing mobile applications, it’s always cool to add some effects or transitions. But, while for example FlashLite has a nice builtin support for them, with J2ME you have to hand-code even the simplest movement (and this is the main reason why most J2ME apps are all but attractive).

    So, here’s a first class that you can use to add an “explode” effect to images in a straightforward way. How to do it? Here we come:

    1. Download the ExplodingImage.java source code and put it straight in your project
    2. Instantiate an ExplodingImage this way:
      //get your Image
      Image sourceImage = Image.createImage("/image.png");
      //and then use it in ExplodingImage constructor
      ExplodingImage image = new ExplodingImage(sourceImage , 5, 8, 8);

      The ExplodingImage constructor accepts the following arguments:

      • An Image instance
      • An int representing the “level” for the exploding effect, that is the strength of the effect itself (higher the level, stronger the effect).
      • The last 2 int arguments represent the horizontal and vertical pieces of the exploded image.
    3. Start the explode effect with the explode() method, that will accept the effect duration as argument:
      image.explode(2000L);
    4. To paint it, simply use its paint() method, very similary to the Graphics drawImage() one. For example, in a Canvas paint() method, you can do something like this:
      protected void paint(Graphics g)
      {
      	g.setColor(0xffffff);
      	g.fillRect(0, 0, width, height);
      	image.paint(g, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
      }

      To give the effect a “smooth” animation, you should paint it quite frequently (let’s say, not once per second :)). So, always using Canvas, a sample code could be like this:

      public void run()
      {
      	while(true)
      	{
      		repaint();
       
      		try
      		{
      			synchronized(this)
      			{
      				wait(50L);
      			}
      		}
      		catch(Exception e)
      		{
      			e.printStackTrace();
      		}
      	}
      }
    5. To test if the effect has ended, you can simply access your ExplodingImage ended instance variable:
      if(image.ended)
      {
      	//effect-end related code
      }
    6. And you’re done! See it in action here: J2ME image explode effect in action

    Sample source code is available here:

     
  • pit 10:53 am on May 19, 2008 Permalink | Reply
    Tags: , midp 1.0, rotate image, source code   

    Rotating images in J2ME using MIDP 1.0 

    So you’re still using MIDP 1.0 uh? And maybe you need to rotate an image?

    J2ME rotate image screenshot

    If this is your case, you could find useful this simple function:

    public static Image rotateImage(Image image, int angle) throws Exception
    {
    	if(angle == 0)
    	{
    		return image; 
    	}
    	else if(angle != 180 && angle != 90 && angle != 270)
    	{
    		throw new Exception("Invalid angle");
    	}
     
    	int width = image.getWidth();
    	int height = image.getHeight();
     
    	int[] rowData = new int[width];
    	int[] rotatedData = new int[width * height];
     
    	int rotatedIndex = 0;
     
    	for(int i = 0; i < height; i++)
    	{
    		image.getRGB(rowData, 0, width, 0, i, width, 1);
     
    		for(int j = 0; j < width; j++)
    		{
    			rotatedIndex = 
    				angle == 90 ? (height - i - 1) + j * height : 
    				(angle == 270 ? i + height * (width - j - 1) : 
    					width * height - (i * width + j) - 1
    				);
     
    			rotatedData[rotatedIndex] = rowData[j];
    		}
    	}
     
    	if(angle == 90 || angle == 270)
    	{
    		return Image.createRGBImage(rotatedData, height, width, true);
    	}
    	else
    	{
    		return Image.createRGBImage(rotatedData, width, height, true);
    	}
    }

    So, how can you use it? Nothing more than:

    Image original = Image.createImage("/original_image.png");
     
    Image rotated_image = rotateImage(original, 90);
     
  • pit 4:06 pm on May 16, 2008 Permalink | Reply
    Tags: , , date field, date item, date picker, , source code   

    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:
      calendar.initialize();
    5. Now, to paint it, you can simply call its paint() method from your Canvas paint(), like this:
      protected void paint(Graphics g)
      {
          g.setColor(0xffffff);
          g.fillRect(0, 0, getWidth(), getHeight());
          calendar.paint(g);
      }
    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)
          {
              Display.getDisplay(midlet).setCurrent(
                  new Alert("Selected date", calendar.getSelectedDate().toString(), null, AlertType.CONFIRMATION)
              );
          }
          else
          {
              calendar.keyPressed(keyCode);
              repaint();
          }
      }

      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

      Hi,

      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
      com.sun.kvem.ktools.ExecutionException
      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:
      replace
      this.weeks = (int)Math.ceil(((double)getStartWeekday() + getMonthDays()) / 7);
      by:
      this.weeks = (int)(0.9 + ((double)getStartWeekday() + getMonthDays()) / 7);

      It’s working

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

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

  • pit 4:59 pm on May 12, 2008 Permalink | Reply
    Tags: file upload, , http, , multipart request, post, source code, upload image   

    HttpMultipartRequest: simple file uploads with J2ME 

    Today’s code is related to file uploads using J2ME. We’ll use Http POST MultiPart requests to handle and transfer data from J2ME application to server; since there is no builtin support for MultiPart, we’ll have to build the request body by hand.

    j2me file upload sample screenshot

    Code is limited to 1 class only (HttpMultipartRequest), that will be easy to include and easy in your code, just instatiate it with its constructor:

    HttpMultipartRequest(String url, Hashtable params,
    String fileField, String fileName,
    String fileType, byte[] fileBytes)

    and then send data to server (and get response) with its send() method. As you can see from the constructor, this implementation support also parameter passing, that will be posted to server together with the file bytes.

    Detailed and explained code (with sample client and server code) is available here: HTTP Post multipart file upload with J2ME Wiki article. To directly download source code, click here.

     
    • Girish 10:07 am on February 11, 2009 Permalink

      Hi! I have tried using the class in a MIDlet, but I cannot make it work. Can you help me? I’ve posted that on a forum, but I haven’t found any help yet.
      http://discussion.forum.nokia.com/forum/showthread.php?p=541133

    • Kapil Katiyar 9:45 am on September 15, 2011 Permalink

      Thanks

    • sabri 9:29 pm on November 30, 2012 Permalink

      hi …
      thanx for ur help … the code working success full except the picture cann’t shown after saved on server because viewer can’t open this picture because the fi;e appears to be damaged …
      and the size on server is larger than the size on mobile …
      please help me to solve this problem ….
      thanx

  • pit 3:02 pm on May 5, 2008 Permalink | Reply
    Tags: darts, , , source code   

    J2ME game code: let’s play Darts! 

    Darts is an ideal game for mobile users, since it does only require few seconds for a match, and could be really helpful while waiting for a bus.. (If you must wait a bus in Rome, it’s easy you’ll become a Darts champion within a day :))

    J2ME game darts screenshot

    This simple game was originally included, as easter egg, in the midlet built for 2007 Edition of Rome JavaDay, to help folks being awake during long talks :) For a live test you can go directly to the emulator page.

    2007 Rome JavaDay Midlet screenshot

    Now, It’s source code is fully available to everyone to (ab)use, and please be kind with me for the total lack of comments…

    Here is the source code, and the full sample midlet if you want to try it out on your phone.

     
    • sejal 3:55 pm on April 5, 2011 Permalink

      hey…when i execute this code on wtk..its showing me errors saying dat

      package com.jappit.japdarts.app does not exist
      import com.jappit.japdarts.app.JapDarts;
      ^
      package com.jappit.japdarts.utils does not exist
      import com.jappit.japdarts.utils.ScoreManager;
      ^
      can u plz help me with this..where do i get the functions and variables in the package package com.jappit.japdarts.display; from ?…pls reply asap !!

    • Renniel 4:09 pm on October 8, 2011 Permalink

      where is the code sir?? thnaks

c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
shift + esc
cancel