目前我想要这个程序做的就是运行没有任何编译错误。基本上,我需要做的是打开框架,然后选择帧时,如果我按下UP箭头键,它将将箭头[0]设置为true,当我释放它时,它将将其设置为false(与右、下和左)...
我的代码将编译。但是,当我尝试运行它时,我不断收到此错误。
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)
我以前做过一个和这个有点相似的程序,但我从来没有遇到过这个问题。我原本以为是因为“frame.addKeyListener;” 或“frame.setFocasable(true);” 但我试着把这些线去掉,它仍然出现了错误......
这是我正在运行的代码,任何解决此问题的帮助都会有所帮助。
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();
}
}