我有问题引用Timer的ActionListener类。我想在Java显示显示时间的对话框并在点击“Yes”后重新开始之后停止定时器。ActionListener类引用问题
这是我目前有:
public class AlarmClock
{
public static void main(String[] args)
{
boolean status = true;
Timer t = null;
ActionListener listener = new TimePrinter(t);
t = new Timer(10000, listener);
t.start();
while(status)
{
}
}
}
class TimePrinter implements ActionListener
{
Timer t;
public TimePrinter(Timer t)
{
this.t = t;
}
public void actionPerformed(ActionEvent event)
{
t.stop(); //To stop the timer after it displays the time
Date now = Calendar.getInstance().getTime();
DateFormat time = new SimpleDateFormat("HH:mm:ss.");
Toolkit.getDefaultToolkit().beep();
int choice = JOptionPane.showConfirmDialog(null, "The time now is "+time.format(now)+"\nSnooze?", "Alarm Clock", JOptionPane.YES_NO_OPTION);
if(choice == JOptionPane.NO_OPTION)
{
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null, "Snooze activated.");
t.start(); //To start the timer again
}
}
}
然而,这个代码给出了一个空指针异常错误。有没有其他方法可以引用定时器?
有完全相同的鸡与鸡蛋问题,这是一个很好的解决方案,谢谢! – sage88 2013-09-28 23:14:31