第8回 キーボードに合わせてグラフィックを動かす
本文へ戻る
リスト1 ImageDemo.java
-----------------------
import com.nttdocomo.ui.*;
import com.nttdocomo.io.*;
class ImageCanvas extends Canvas {
Image img;
int x,y;
int height,width;
ShortTimer st;
int TIMER_ID = 1; // タイマーID。重複していなければ何でもいい
int TIMER_TICK = 100; // タイマーの時間(ミリ秒)
ImageCanvas() {
MediaImage im = MediaManager.getImage( "resource:///nya.GIF" );
try {
im.use();
}
catch( ConnectionException e ) {
}
catch( UIException e ) {
// エラー
}
img = im.getImage();
height = img.getHeight(); // イメージの高さ
width = img.getWidth(); // イメージの幅
x = y = 0; // 描画の初期位置
st = ShortTimer.getShortTimer(this, TIMER_ID, TIMER_TICK, false );
}
public void paint(Graphics g) {
if( img != null )
// イメージの描画
{
g.drawImage( img , x, y );
}
}
public void processEvent( int type, int param ) {
int key = getKeypadState();
// 方向キーが押されたら秒が位置を変える
if( (key & (1 << Display.KEY_DOWN) ) != 0 ) {
y += 2;
}
if( (key & (1 << Display.KEY_UP) ) != 0 ) {
y -= 2;
}
if( (key & (1 << Display.KEY_LEFT) ) != 0 ) {
x -= 2;
}
if( (key & (1 << Display.KEY_RIGHT) ) != 0 ) {
x += 2;
}
// イメージの表示領域+2ドット分を再描画する
// 速度が遅くなるので画面全体を再描画するのは
// 止めたほうがいい。
repaint(x-2,y-2,width+2,height+2);
// 念のためタイマーを止め
st.stop();
// ワンショットタイマーを仕掛ける
st.start();
}
}
public class ImageDemo extends IApplication {
public void start() {
ImageCanvas ic = new ImageCanvas();
Display.setCurrent( ic );
}
}
------------------
本文へ戻る
Copyright © ITmedia, Inc. All Rights Reserved.