ToggleMenuItem.java

/**
* 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.explonoid.menu;

import javax.microedition.lcdui.game.Sprite;

/**
 * Represents a menu item that can be toggled on and off.
 */
public class ToggleMenuItem
        extends MenuItem {

    private volatile boolean on = false;

    public ToggleMenuItem(Sprite sprite) {
        super(sprite);
    }

    public void set(boolean on) {
        this.on = on;
        sprite.setFrame(getFrame());
    }

    public boolean toggle() {
        this.on = !this.on;
        sprite.setFrame(getFrame());
        return on;
    }

    protected int getFrame() {
        return super.getFrame() + (on ? 2 : 0);
    }

    public boolean isOn() {
        return on;
    }
}