Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 2026)

Previous: Shape

Scenes


// This example shows the use of a Scene interface in a
// graphics program (using the Processing libraries).
//
// Scene.java
//


public interface Scene
{
    public void display();
    public void keyPressed();
}
//
// Scene_Start.java
//


import processing.core.*;


public class Scene_Start implements Scene
{
    public Scene_Start(PApplet p)
    {
        this.p = p;
    }

    public void display()
    {
        p.background(0, 0, 255);
        p.textSize(64);
        p.textAlign(PApplet.CENTER);
        p.text("My Awesome Game", p.width/2, p.height/2);
    }

    public void keyPressed() {}

    private PApplet p;
}
//
// Scene_Play.java
//


import processing.core.*;


public class Scene_Play implements Scene
{
    public Scene_Play(PApplet p)
    {
        this.p = p;
        this.x = p.width/2;
        this.y = p.height/2;
    }

    public void display()
    {
        p.background(0);
        p.fill(0, 255, 0);
        p.ellipse(x, y, 50, 50);
    }

    public void keyPressed()
    {
        if (p.keyCode == PApplet.RIGHT)
            x += 25;
        else if (p.keyCode == PApplet.LEFT)
            x -= 25;
        else if (p.keyCode == PApplet.DOWN)
            y += 25;
        else if (p.keyCode == PApplet.UP)
            y -= 25;
    }

    private int x;
    private int y;

    private PApplet p;
}
//
// Scene_End.java
//


import processing.core.*;


public class Scene_End implements Scene
{
    public Scene_End(PApplet p)
    {
        this.p = p;
    }

    public void display()
    {
        p.background(255, 0, 0);
        p.textSize(64);
        p.textAlign(PApplet.CENTER);
        p.text("GAME OVER", p.width/2, p.height/2);
    }

    public void keyPressed() {}

    private PApplet p;
}
//
// Game.java
//


import processing.core.*;
import java.util.*;


public class Game extends PApplet
{
    public void settings()
    {
        size(800, 800);
    }

    public void setup()
    {
        scenes = new ArrayList<Scene>(); 
        scenes.add(new Scene_Start(this));
        scenes.add(new Scene_Play(this));
        scenes.add(new Scene_End(this));

        current = 0;
    }

    public void draw()
    {
        background(0);

        // call the current Scene display() function
        scenes.get(current).display();
    }
    
    public void keyPressed()
    {
        if (key == ' ')
        {
           current++;
           if (current >= scenes.size())
               current = 0;
        }

        // call the current Scene keyPressed() function
        scenes.get(current).keyPressed();
    }

    private ArrayList<Scene> scenes;
    private int current;

    public static void main(String[] args)
    {
        PApplet.main("Game");
    }
}

Next: