簡體   English   中英

如何在鼠標退出事件上啟動Timer並在鼠標輸入事件上停止相同的Timer?

[英]How to start a Timer on a mouse exit event and stop that same Timer on a mouse enter event?

我有一個名為reminderList的列表。

當鼠標單擊列表中的項目並且鼠標退出列表時,我想要一個計時器啟動。

當鼠標進入列表時,我希望該計時器停止,如果它仍在運行。

當鼠標再次退出列表時,我想要重新啟動相同的計時器。

public void waitReminderList(int status) {
    Timer timer = new Timer(10000, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            reminderList.clearSelection();
            dismissReminder.setEnabled(false);
        }
    });
    if (status == 0) {
        if (!reminderList.isSelectionEmpty()) {
            timer.setRepeats(false);
            timer.restart();
            timer.start();
        }
    } else if (status == 1) {
        if (!reminderList.isSelectionEmpty()) {
            timer.stop();
        }
    }

private void reminderListMouseExited(java.awt.event.MouseEvent evt) {                                         
    waitReminderList(0);
} 

private void reminderListMouseEntered(java.awt.event.MouseEvent evt) {                                          
    waitReminderList(1);
}

問題是:計時器在啟動后不會停止或重新啟動或執行任何操作,但我需要它。

我的問題的解決方案是有一個int,然后我可以通過int的值控制我想要的計時器。 但它不起作用,計時器不停...

那我做錯了什么?

我知道還有其他這樣的問題,但是,我仍然是相當新的java,我不明白給出的答案。

謝謝

問題是每次調用waitReminderListwaitReminderList創建一個新的Timer 以前運行的任何Timer對象都不會停止。 由於您希望單個Timer在方法移動引用,例如在類級別。

不要在waitReminderList()方法中繼續創建新的Timer。 您應該將Timer定義為類變量。

然后你可以根據需要停止/啟動它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM