SplashScreenView.java

/*
 * Copyright © 2012 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.spacemission;

import javax.microedition.lcdui.game.GameCanvas;
import java.util.*;
import javax.microedition.lcdui.*;

public class SplashScreenView
        extends GameCanvas {

    private Image[] images;
    private int currentImage = -1;
    private int timeout;
    private Displayable next;
    private Display display;
    private Timer timer;

    public SplashScreenView(Display display, Displayable next, Image[] images,
                            int timeout) {
        super(false);
        this.images = images;
        this.timeout = timeout;
        this.next = next;
        this.display = display;
        this.setFullScreenMode(true);
        if ((images != null) && (images.length > 0)) {
            this.currentImage = 0;
        }
        else {
            this.currentImage = -1;
        }
    }

    public void paint(Graphics graphics) {
        if(currentImage == 0) {
            graphics.setColor(0xffffff);
        } else {
            graphics.setColor(0x000000);
        }
        graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
        if (currentImage != -1) {
            graphics.drawImage(images[currentImage], getWidth() / 2, getHeight() / 2, Graphics.HCENTER
                    | Graphics.VCENTER);
        }
    }

    protected void pointerReleased(int x, int y) {
        showNextImage();
    }

    protected void keyPressed(int keyCode) {
        showNextImage();
    }

    protected void showNotify() {
        if ((images != null) && (images.length > 0)) {
            this.currentImage = 0;
        }
        else {
            this.currentImage = -1;
        }
        scheduleTimer();
    }

    private void scheduleTimer() {
        try {
            this.timer = new Timer();
            this.timer.schedule(new CountDown(), timeout);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void closeSplashScreen() {
        this.timer.cancel();
        this.currentImage = -1;
        repaint();
        this.display.setCurrent(next);
    }

    private void showNextImage() {
        if (currentImage + 1 >= images.length) {
            closeSplashScreen();
        }
        else {
            if (this.currentImage != -1) {
                currentImage++;
                repaint();
                scheduleTimer();
            }
        }
    }

    private class CountDown
            extends TimerTask {

        public void run() {
            showNextImage();
        }
    }
}