Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Revision as of 04:29, 8 August 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Canvas Loading Bar in Java ME

From Wiki
Jump to: navigation, search
Article Metadata
Created: jappit (30 Apr 2008)
Last edited: hamishwillee (08 Aug 2013)

A simple loading bar to be used on Canvas when doing long operations. You can see a live preview here: Canvas Loading bar emulator

J2me loading bar.png

We'll start defining some instance variables, that we'll use within our code:

public long stepInterval = 250L;
public int width = 0;
public int height = 0;
int padding = 0;
int color = 0x000000;
int squares = 0;
int squareWidth = 0;
int currentSquares = 0;
Timer stepTimer = null;

Now the bar constructor, with its arguments:

  • bar size (width and height)
  • padding between squares
  • number of squares to be used
  • squares color
public LoadingBar(int width, int height, int padding, int squares, int color)
this.width = width;
this.height = height;
this.squares = squares;
this.color = color;
this.padding = padding;
this.squareWidth = (width - padding) / (squares) - padding;

Paint method is quite straightforward:

public void paint(Graphics g)
for(int i = 0; i < currentSquares; i++)
g.fillRect(i * (squareWidth + padding), 0, squareWidth, height);

Finally, the animation logic, where we'll use a Timer, and expose start() and stop() methods to control Bar animation:

public void start()
stepTimer = new Timer();
stepTimer.schedule(new TimerTask()
public void run()
stepInterval, stepInterval
public void stop()
void step()
currentSquares = (currentSquares + 1) % (squares + 1);
This page was last modified on 8 August 2013, at 04:29.
139 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.