2

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

ただし、このコードではヌル ポインター例外エラーが発生します。タイマーを参照できる他の方法はありますか?

4

1 に答える 1

2

両方のクラスのコンストラクターは相互に参照する必要があるため、ここでは鶏が先か卵が先かという問題があります。なんらかの方法でサイクルを中断する必要があります。最も簡単な方法はTimer、リスナーなしでを構築し、次にリスナーを構築して、それをタイマーに追加することです。

    t = new Timer(10000, null);
    ActionListener l = new TimePrinter(t);
    t.addActionListener(l);

または、コンストラクター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);

いずれにせよ、最終結果は同じです。

于 2013-02-20T16:02:02.480 に答える