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