jwill / lanterna

Automatically exported from code.google.com/p/lanterna
GNU Lesser General Public License v3.0
0 stars 0 forks source link

NullPointerException at Key#getKind #99

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Let's say I have a java like this:

package javagame;

import com.googlecode.lanterna.input.*;
import com.googlecode.lanterna.screen.*;
import com.googlecode.lanterna.terminal.*;
import com.googlecode.lanterna.terminal.swing.*;

public class JavaGame {

    public static Screen screen = new Screen(new SwingTerminal(60, 25));

    public static void main(String[] args) {
        screen.startScreen();
        while (true) {
            Key key = screen.readInput();
            if (key.getKind() == Key.Kind.Escape)
                break;
        }
        screen.stopScreen();
    }

}

And let's say I compile and run it. Whenever it starts up, it gives me a 
NullPointerException.

Exception in thread "main" java.lang.NullPointerException
    at javagame.JavaGame.main(JavaGame.java:16)

And whenever I press escape, the program doesn't stop.

Original issue reported on code.google.com by samfranc...@gmail.com on 1 Feb 2014 at 10:36

GoogleCodeExporter commented 9 years ago
You need to check whether a key was actually pressed. A working input loop:

public static void main(String[] args) throws InterruptedException {
    screen.startScreen();
    while (true) {
        Key key = screen.readInput();
        if (key != null) {
            if (key.getKind() == Key.Kind.Escape)
                break;
        }
        Thread.sleep(1);
    }
    screen.stopScreen();
}

Original comment by unixprog@googlemail.com on 13 Feb 2014 at 11:58

GoogleCodeExporter commented 9 years ago
Yes, readInput() will return null if no key was pressed.

Original comment by mab...@gmail.com on 16 Feb 2014 at 7:30