我的一个朋友和我必须用Java编写大学游戏。我正在尝试在我们创建的工具栏中实现一个小时钟。当我运行代码时,出现此错误:
线程“ Thread-0”中的异常java.lang.NullPointerException
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
的常量)之外。