gpt4 book ai didi

java.lang.NullPointerException | java.lang.NullPointerException我的时钟不工作

转载 作者:行者123 更新时间:2023-12-02 06:09:13 28 4
gpt4 key购买 nike

我和我的一个 friend 必须为大学用 Java 编写一个游戏。我正在尝试在我们创建的工具栏中实现一个小时钟。当我运行代码时,出现此错误:

Exception in thread "Thread-0" java.lang.NullPointerException at GameTimer.run(GameTimer.java:29)

KodeKsToolBar.java

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;

import javax.swing.*;

public class KodeKsToolBar extends JToolBar{
private static final long serialVersionUID = 1L;
public static JLabel timeLabel;

public KodeKsToolBar(GUI listener, Dimension size){
//unimported Stuff hidden
//...
JLabel timeLabel = new JLabel(GameTimer.currentTime);
GameTimer t = new GameTimer();
t.start();
//clock = new Clock(this);
//clock.start();

setFloatable(false);
add(ToolBarItem_NGame);
add(ToolBarItem_Load);
add(ToolBarItem_Save);
add(ToolBarItem_Resign);
add(toolBarItem_PauseResume);
add(timeLabel);
}
}

GameTimer.java:

import java.awt.*;
import java.awt.event.*;
import java.text.DateFormat;
import java.util.Date;



public class GameTimer extends Thread {
static boolean running = true;
int milliSeconds = 0;
int seconds = 0;
int minutes = 0;
static String currentTime = "00:00";

public void run() {
while(running) {
milliSeconds++;
if(milliSeconds > 999){
milliSeconds = 0;
seconds++;
}
if(seconds > 59){
seconds = 0;
minutes++;
}
KodeKsToolBar.timeLabel.setText(getTime()); // <-- This is the line mentioned above, which causes the error
try {
Thread.sleep(10);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}

public String getTime() {
currentTime = minutes + ":" + seconds;
return currentTime;
}
}

最佳答案

您正在访问静态变量

KodeKsToolBar.timeLabel

但在 KodeKsToolBar 构造函数中初始化同名的局部变量

JLabel timeLabel = new JLabel(GameTimer.currentTime);

删除JLabel以保留。-

timeLabel = new JLabel(GameTimer.currentTime);

PS:正如 @Overcraft Full of Eels 所说,请记住,除了常量(声明为 final 的常量)之外,实例变量应该是非静态的。

关于java.lang.NullPointerException | java.lang.NullPointerException我的时钟不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338635/

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