At the moment all I want this program to do is run without any compile errors. Basically, what I need it to do is open the frame and then when the frame is selected, if I press the up arrow key it will set arrows[0] to true and when I release it it will set it to false (same with right, down, and left as well)...
My code will compile. However, I keep getting this error when I try to run it.
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
I've done a program somewhat similar to this before and I never had this problem. I originally thought it was because of the "frame.addKeyListener;" or the "frame.setFocasable(true);" but I tried taking those lines out and it still came up with the error...
Here's the code that I am running, any help to fix this problem would be helpful.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.*;
public class arrowTest extends JApplet implements KeyListener {
private boolean[] arrows = new boolean[4];
private int x = 0;
private int y = 0;
public arrowTest() {
}
// Handle the key typed event from the text field.
public void keyTyped(KeyEvent e) {
System.out.println("KEY TYPED: ");
}
// Handle the key-pressed event from the text field.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
arrows[0] = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
arrows[1] = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
arrows[2] = true;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
arrows[3] = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
arrows[0] = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
arrows[1] = false;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
arrows[2] = false;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
arrows[3] = false;
}
}
public void run() {
JFrame frame = new JFrame();
JApplet applet = new arrowTest();
frame.add(applet);
frame.setTitle("arrowTest");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setVisible(true);
frame.addKeyListener(this);
frame.setFocusable(true);
}
public void main(String[] args) {
run();
}
}