java - ActionListener 类的引用问题

标签 java swing timer actionlistener

我在将 Timer 引用到 ActionListener 类时遇到问题。我想在Java显示显示时间的对话框后停止计时器,并在单击"is"后再次启动。

这是我目前拥有的:

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);

或者,您可以向 TimePrinter 添加 setter,而不是将 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);

无论哪种方式,最终结果都是相同的。

关于java - ActionListener 类的引用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14984240/

相关文章:

java - 支持 MySQL 和 Oracle 的最佳实践

java - 使用 swing 包的简单 java 表单需要日历中的指导吗?

java - JButton 位于类中,actionlistener 位于 main 中

javascript - Javascript 中的秒表比正常时间慢

java - 如何暂停我的 Java 程序 2 秒

javascript - setTimeout 与 setInterval - 使用的最佳实践

java - (架构)为 angular2 应用程序抓取数据。直接检查MongoDB还是我的Java REST?

java - GridView 超出内存预算

java - 在不影响外观的情况下更改 JComboBox 弹出窗口大小?

java - 从多个 JLabel 获取鼠标点击输入的较小程序