gpt4 book ai didi

java - JFrame 的 NullPointerException

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:36:13 24 4
gpt4 key购买 nike

目前我想让这个程序做的就是在没有任何编译错误的情况下运行。基本上,我需要做的是打开框架,然后选择帧时,如果我按下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();

}
}

最佳答案

At the moment all I want this program to do is run without any compile errors.

郑重声明,您的程序确实运行时没有“编译错误”。发生的事情是在程序运行期间抛出空指针异常 (NPE),而不是编译错误。您需要找出导致 NPE 的线路,然后通过确保所有引用变量在使用前都已初始化来修复它。

而且,您不应该为此使用 KeyListeners,而应该使用 Key Bindings——两者有很大的不同。键绑定(bind)教程将解释所有内容。一开始它可能看起来有点令人生畏,但不要放弃,按照示例操作,您很快就会使用它。

当您尝试创建 JFrame 时,为什么还要使用 JApplet?这有点古怪。

编辑2
而且您的代码甚至不会运行,因为您的主要方法是非静态的。如果您将程序作为实际的 JFrame 运行,则需要向我们展示您使用的实际代码。此代码没有可行的 main 方法,因此不是。

编辑 3
不,静态不是你的问题,你仍然需要学习使用键绑定(bind)并且不要在你拥有的这个奇怪的嵌合体中混合 JApplet 和 JFrame 代码。

关于java - JFrame 的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7533469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com