Catching the key pressed and repeat event in the Canvas of J2ME....
the following code is for catching the key pressed and repeat event in the Canvas of J2ME....import com.sun.perseus.model.CanvasUpdateListener;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
/*
* MyCanvas.java
*
* Created on August 27, 2007, 3:25 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
/**
*
* @author iftee
*/
public class MyCanvas extends Canvas {
/** Creates a new instance of MyCanvas */
int rectX = 0, rectY = 0, rectWidth = 50, rectHeight = 50 ,displacement = 5, keyCode = 0;
boolean keepGoing = true;
Graphics gra;
public MyCanvas() {
}
protected void paint(Graphics g)
{
gra = g;
if(rectX < rectx =" 0;" recty =" 0;"> this.getWidth() - rectWidth) rectX = this.getWidth() - rectWidth;
else if(rectY > this.getHeight() - rectHeight) rectY = this.getHeight() - rectHeight;
g.setColor(0, 0, 0);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(255, 0, 0);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
}
protected void keyRepeated(int key)
{
switch (getGameAction(key))
{
case RIGHT:
System.out.println("right");
rectX += displacement;
gra.fillRect(70, 70, 80, 80);
break;
case LEFT:
System.out.println("left");
rectX -= displacement;
break;
case UP:
System.out.println("up");
rectY -= displacement;
break;
case DOWN:
System.out.println("down");
rectY += displacement;
break;
}
repaint();
}
protected void keyPressed(int key)
{
switch (getGameAction(key))
{
case RIGHT:
System.out.println("right");
rectX += displacement;
break;
case LEFT:
System.out.println("left");
rectX -= displacement;
break;
case UP:
System.out.println("up");
rectY -= displacement;
break;
case DOWN:
System.out.println("down");
rectY += displacement;
break;
}
repaint();
}
}
No comments:
Post a Comment