MenuItem.java
/*
* Copyright © 2011 Nokia Corporation. All rights reserved.
* Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
* Oracle and Java are trademarks or registered trademarks of Oracle and/or its
* affiliates. Other product and company names mentioned herein may be trademarks
* or trade names of their respective owners.
* See LICENSE.TXT for license information.
*/
package com.nokia.example.racer.views.components;
import com.nokia.example.racer.helpers.ImageLoader;
import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public abstract class MenuItem {
protected Image normal;
protected Image highlighted;
private boolean ishighlighted;
private int x = 0;
private int y = 0;
public MenuItem() {
}
public final void init(String imgUrl_unpressed, String imgUrl_pressed) {
ImageLoader loader = ImageLoader.getInstance();
try {
normal = loader.loadImage(imgUrl_unpressed);
highlighted = loader.loadImage(imgUrl_pressed);
}catch(IOException io) {
}
}
/**
* Subclasses overide this dummy implementation.
*/
public abstract void onSelected();
public void render(Graphics g) {
int anchor = Graphics.TOP|Graphics.LEFT;
if(ishighlighted) {
g.drawImage(highlighted, x, y, anchor);
}else {
g.drawImage(normal, x, y, anchor);
}
}
public void setPosition(int x , int y) {
this.x = x;
this.y = y;
}
private final Rectangle getArea() {
return new Rectangle(x, y, normal.getWidth(), normal.getHeight());
}
public final boolean isPressed(int x, int y) {
return getArea().isPointInside(x, y);
}
/**
* When you add menuitem to canvas you must call this method from the pointerpressed method in canvas class to make
* menuitem work.
* @param x
* @param y
*/
public void pointerPressed(int x, int y) {
if(isPressed(x, y)) {
ishighlighted = true;
}else {
ishighlighted = false;
}
}
public void pointerReleased(int x, int y) {
ishighlighted = false;
if(isPressed(x, y))
onSelected();
}
public void setActive() {
ishighlighted = true;
}
public void setInactive() {
ishighlighted = false;
}
}