目前我希望這個程序要做的就是運行時沒有任何編譯錯誤。基本上,我需要做的是打開框架,然後當框架被選中時,如果我按下向上箭頭鍵將箭頭[0]設置爲true,當我釋放它將它設置爲false(與向右,向下,向左)...帶有JFrame的NullPointerException
我的代碼將被編譯。但是,當我嘗試運行它時,我不斷收到此錯誤。
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();
}
}
由DrJava中的錯誤引起。看到這裏:http://stackoverflow.com/questions/7911004/nullpointerexcetion-native-method-accessor-hashing-words-issue –