Tuesday, June 30, 2009

Adding a scrollbar

Sometimes you have more data to show than available space. One way to make this clear to the user is presenting a scroll bar.
Lets update our custom alert to paint a scroll bar when necessary.
Below is the source code of my simple scroll bar component:

import javax.microedition.lcdui.Graphics;

public class Scrollbar {

private int x, y, width, height;
private int total; // how much you have to present
private int position; // what you are presenting
private int backgroundColor = 0xffffff;
private int foregroundColor;
private int indicatorHeight;

/**
* @param part how much can be presented to the user at a time
*/
public Scrollbar(int x, int y, int w, int h,
int part, int total)
{
this.x = x; this.y = y; this.width = w; this.height = h;
this.total = total;
// the indicator height is calculated as a proportion of h
indicatorHeight = (part * h) / total;
// sanity test
if (indicatorHeight >= height) {
indicatorHeight = height / 2;
}
}

public void setPosition(int position) {
this.position = position;
}

public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
}

public void setForegroundColor(int foregroundColor) {
this.foregroundColor = foregroundColor;
}

public void paint(Graphics g) {
int indicatorY = (this.position * this.height) / this.total;

// sanity test, can not draw below the height
if (indicatorY + this.indicatorHeight > height) {
indicatorY = height - this.indicatorHeight;
}

g.setColor(this.backgroundColor);
g.fillRect(x, y, width, height);
g.setColor(this.foregroundColor);
g.fillRect(x, indicatorY, width, indicatorHeight);
}
}

Now lets use the scroll bar. Define an Scrollbar attribute and create an instance right after you have initiated your message array:

// how many lines the user can see at a time
int maxLines = this.getHeight() / Font.getDefaultFont().getHeight();

if (maxLines < this.message.length) {
// 10 = scroll bar width. Remember to also subtract this value
// when initiating message array
this.scrollbar = new Scrollbar(getWidth() - 10, 0, 10, getHeight(),
maxLines, this.message.length)
}

At commandAction right after you update messageFirstLineShown:

if (this.scrollbar != null) {
this.scrollbar.setPosition(this.messageFirstLineShown);
}

At paint method:

if (this.scrollbar != null) {
this.scrollbar.paint(g);
}

Now, when the user press Next command he will see the scroll bar indicator move downwards.
This is a simple implementation with a simple usage. Feel free to change any part of it on your project.

Related topics:

1 comment:

Unknown said...
This comment has been removed by a blog administrator.