Here’s the trick how you can add touchscreen scrolling to your J2ME applications. The key to touchscreen support is the Canvas class and its’ methods pointerPressed, pointerDragged and pointerReleased. These events are called when user puts finger on the screen (pressed) and drags the finger (dragged) and finally when removes the finger (released). Each method has the x and y coordinates for the pointer action.
The scrolling is implemented with the pointerDragged event. We store the current location of the canvas to variables verticalLoc and horizontalLoc. When finger (pointer) is dragged then location is changed according to the dragged amount. Variables are used on paint method to draw the area so that it is scrolled that correctly. You can also see from the sample code how you can draw background with repeatable pattern image.
-
-
// Current location
-
private int verticalLoc, horizontalLoc;
-
// Last pointer (finger) location
-
private int lastX, lastY;
-
// Background image size
-
private static final int IMAGE_WIDTH = 183;
-
private static final int IMAGE_HEIGHT = 183;
-
-
public ScrollingCanvas() {
-
verticalLoc = 0;
-
horizontalLoc = 0;
-
setFullScreenMode(true);
-
}
-
-
-
// Draw background with pattern image
-
int x = horizontalLoc % IMAGE_WIDTH;
-
if(x>0) {
-
x -= IMAGE_WIDTH;
-
}
-
int origX = x;
-
-
int y = verticalLoc % IMAGE_HEIGHT;
-
if(y>0) {
-
y -= IMAGE_HEIGHT;
-
}
-
-
boolean verticalDone = false;
-
while(!verticalDone) {
-
boolean horizontalDone = false;
-
while(!horizontalDone) {
-
g.drawImage(
-
ImageRepository.getBackground(),
-
x += IMAGE_WIDTH;
-
if(x>getWidth()) {
-
horizontalDone = true;
-
}
-
}
-
x = origX;
-
y += IMAGE_HEIGHT;
-
if(y>getHeight()) {
-
verticalDone = true;
-
}
-
}
-
}
-
-
/**
-
* Finger is pressed on screen
-
* @param x coordinate
-
* @param y coordinate
-
*/
-
protected void pointerPressed(int x, int y) {
-
lastX = x;
-
lastY = y;
-
}
-
-
/**
-
* Finger is dragged on screen
-
* @param x coordinate
-
* @param y coordinate
-
*/
-
protected void pointerDragged(int x, int y) {
-
// Calculate how much we moved horizontally
-
int deltaHorizontal = lastX – x;
-
horizontalLoc -= deltaHorizontal;
-
lastX = x;
-
-
// Calculate how much we moved vertically
-
int deltaVertical = lastY – y;
-
verticalLoc -= deltaVertical;
-
lastY = y;
-
-
// Repaint the screen since we have scrolled
-
repaint();
-
}
-
-
}
Here is a video of running this demonstration app in Nokia N97 SDK emulator: