Java 引用ActionListener类的问题

Java 引用ActionListener类的问题,java,swing,timer,actionlistener,Java,Swing,Timer,Actionlistener,我无法将计时器引用到ActionListener类。我想在Java显示显示时间对话框后停止计时器,并在单击“是”后再次启动 这就是我目前拥有的: public class AlarmClock { public static void main(String[] args) { boolean status = true; Timer t = null; ActionListener listener = new TimePr

我无法将计时器引用到ActionListener类。我想在Java显示显示时间对话框后停止计时器,并在单击“是”后再次启动

这就是我目前拥有的:

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
        }
    }
}

然而,这段代码给出了一个空指针异常错误。有没有其他方法可以引用计时器?

这里有一个鸡和蛋的问题,因为两个类的构造函数都需要相互引用。您需要以某种方式打破这个循环,最简单的方法是在没有侦听器的情况下构造
计时器
,然后构造侦听器,然后将其添加到计时器中:

    t = new Timer(10000, null);
    ActionListener l = new TimePrinter(t);
    t.addActionListener(l);
或者,您可以将setter添加到
TimePrinter
,而不是将
Timer
传递给其构造函数:

class TimePrinter implements ActionListener
{   
    Timer t;

    public TimePrinter() {}

    public setTimer(Timer t)
    {
        this.t = t;
    }
然后呢

    TimePrinter listener = new TimePrinter();
    t = new Timer(10000, listener);
    listener.setTimer(t);

无论哪种方式,最终结果都是一样的。

有完全相同的鸡和蛋问题,这是一个很好的解决方案,谢谢!