gpt4 book ai didi

java - 如何修复 "Exception in thread "AWT-EventQueue- 0"java.lang.NullPointerException"?

转载 作者:行者123 更新时间:2023-11-30 03:08:08 27 4
gpt4 key购买 nike

你好,我有一个练习用的小游戏。我可以在屏幕上放置 JLabel,但是当我运行 ActionListener actionPerformed 第三个 if 语句时,它会停止游戏。另外,我不知道要对“线程“AWT-EventQueue-0”java.lang.NullPointerException”中的异常”错误进行更改。谢谢 :)代码如下:

package me.mikail.movement;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class Player extends JComponent implements ActionListener, KeyListener{

Timer time = new Timer(10, this);
private int x = 0, xSpeed = 3, y = 0, ySpeed = 4, stickX = 0, stickY = 400;
private JFrame frame;
private int oneup = 0;
private JLabel info;

public static void main(String[] args){
Player p = new Player();
JFrame frame = new JFrame("Player Practice");
JLabel info = new JLabel(" ");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(p);
frame.getContentPane().setBackground(Color.BLACK);
frame.setResizable(false);
frame.addKeyListener(p);
info.setOpaque(true);
info.setBackground(Color.WHITE);
frame.add(info, BorderLayout.SOUTH);
}

public void paintComponent(Graphics g){
super.paintComponents(g);
//Ball
g.setColor(Color.BLUE);
g.fillRect(x, y, 30, 30);
//Stick
g.setColor(Color.RED);
g.fillRect(stickX, stickY, 75, 10);
time.start();
}
public void points(){
int counter[] = {0,1,2,3,4,5,6,7,8,9,10};
for(int i = 0; i<=oneup; i++){
info.setText("You have "+counter[i]+" point(s)");
}
frame.add(info, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
//Y's 0 is on the top
//X's 0 is on the left
if(x<0){
xSpeed = -(xSpeed);
}
if(x>=470){
xSpeed = -(xSpeed);
}
//when block hits stick
if(y==stickY){
if(x>=(stickX)&&x<=(stickX+75)){
ySpeed = -(ySpeed);
oneup = (1+oneup);
points();
}else{
}
}
if(y<0){
ySpeed = -(ySpeed);
}
if(y>=450){
ySpeed = -(ySpeed);
}
x = (x + xSpeed);
y = (y + ySpeed);
repaint();

}

public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_A|| key == KeyEvent.VK_LEFT){
stickX = (stickX - 50);
}else if(key == KeyEvent.VK_D|| key == KeyEvent.VK_RIGHT){
stickX = (stickX + 50);
}else{
System.out.println("Why did you type that?");
}
}

public void keyReleased(KeyEvent e) {
}

public void keyTyped(KeyEvent e) {
}
}

最佳答案

for(int i = 0; i<=i; i++){
info.setText("You have "+counter[i]+" point(s)");
}

-i<=i总是正确的,无论 i的值。这个for循环永远不会结束...并且在执行此操作时,它可能永远不会真正显示文本。

关于java - 如何修复 "Exception in thread "AWT-EventQueue- 0"java.lang.NullPointerException"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243115/

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