Programming Tutorials

(追記) (追記ここまで)

'double buffering' Sample program in J2ME

By: Charles in J2ME Tutorials on 2007年09月17日 [フレーム]

Double buffering is a technique used to avoid flickering when rendering graphics in J2ME applications. The basic idea is to create an off-screen image and draw everything to that image, and then draw the final image to the screen. This way, the final image appears all at once and there is no flicker caused by the screen being partially updated.

Here's a sample program that demonstrates double buffering in J2ME:

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;
public class DoubleBufferingDemo extends MIDlet {
 private Display display;
 private MyCanvas canvas;
 public void startApp() {
 display = Display.getDisplay(this);
 canvas = new MyCanvas();
 display.setCurrent(canvas);
 }
 public void pauseApp() {}
 public void destroyApp(boolean unconditional) {}
 private class MyCanvas extends Canvas {
 private int x = 0;
 private int y = 0;
 public void paint(Graphics g) {
 // Create an off-screen image and graphics context
 int w = getWidth();
 int h = getHeight();
 int[] buf = new int[w * h];
 Graphics offscreen = Graphics.createImageGraphics(buf, w, h);
 // Draw everything to the off-screen graphics context
 offscreen.setColor(0xffffff);
 offscreen.fillRect(0, 0, w, h);
 offscreen.setColor(0xff0000);
 offscreen.drawLine(0, 0, x, y);
 // Draw the final image to the screen
 g.drawRGB(buf, 0, w, 0, 0, w, h, true);
 }
 public void keyPressed(int keyCode) {
 // Move the line based on user input
 switch (getGameAction(keyCode)) {
 case LEFT:
 x--;
 break;
 case RIGHT:
 x++;
 break;
 case UP:
 y--;
 break;
 case DOWN:
 y++;
 break;
 }
 // Repaint the canvas
 repaint();
 }
 }
}

This program creates a custom Canvas that uses double buffering to draw a line on the screen that can be moved using the arrow keys. The paint() method creates an off-screen image using an integer buffer, draws the line to the off-screen graphics context, and then draws the final image to the screen. The keyPressed() method updates the position of the line and then repaints the canvas to show the new position.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /