/** * Copyright (c) 2012-2013 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.paint.views.components; import com.nokia.example.paint.helpers.ImageLoader; import java.util.Vector; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import javax.microedition.lcdui.game.Sprite; /* * Generic class for buttons. */ public abstract class Button { protected Image pressed; protected Image unpressed; protected Sprite sprite; protected int width; protected int height; protected int x = 0; protected int y = 0; protected boolean isPressed = false; private boolean isSprite = false; private Vector listeners; public Button(String pressed_image_url, String unpressed_image_url) { this(); setImages(pressed_image_url, unpressed_image_url); } public Button() { //default constructor listeners = new Vector(); } protected void setImages(String pressed_image_url, String unpressed_image_url) { ImageLoader loader = ImageLoader.getInstance(); pressed = loader.loadImage(pressed_image_url); unpressed = loader.loadImage(unpressed_image_url); width = pressed.getWidth(); height = pressed.getHeight(); isSprite = false; } protected void setSprite(String sprite_url, int spriteWidth, int spriteHeight) { sprite = new Sprite(ImageLoader.getInstance().loadImage(sprite_url), spriteWidth, spriteHeight); width = sprite.getWidth(); height = sprite.getHeight(); isSprite = true; } public Button(String sprite_url) { setSprite(sprite_url, 46, 41); listeners = new Vector(); } public void addListener(ButtonListener listener) { listeners.addElement(listener); } public abstract void onSelected(); public void render(Graphics g) { if (isSprite) { sprite.setPosition(x, y); sprite.paint(g); } else { if (isPressed) { g.drawImage(pressed, x, y, Graphics.TOP | Graphics.LEFT); } else { g.drawImage(unpressed, x, y, Graphics.TOP | Graphics.LEFT); } } } public void setPosition(int x, int y) { this.x = x; this.y = y; } /** * Calls the onSelected method if x and y are inside the tool area. * @param x * @param y */ public void pressed(int x, int y) { if (x >= this.x && x <= (this.x + width)) { if (y >= this.y && y <= this.y + height) { isPressed = true; } } } public void unpressed(int x, int y) { isPressed = false; if (x >= this.x && x <= (this.x + width)) { if (y >= this.y && y <= this.y + height) { onSelected(); int l = listeners.size(); for (int i = 0; i < l; i++) { ButtonListener listener = (ButtonListener) listeners.elementAt(i); listener.buttonPressed(this); } } } } public int getWidth() { return width; } public int getHeight() { return height; } }