简体   繁体   中英

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

I have a list called reminderList .

When the mouse clicks on an item in the list and the mouse exits the list, i want a timer to start.

When the mouse enters the list, i want that timer to stop, if it is still running.

When the mouse exits the list again, i want that same timer to restart.

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

The problem is: the timer doesn't stop or restart or do anything after it has been started but i need it to.

My solution to the problem was to have an int and then i can control what i want the timer to do by the value of the int. But it didn't work, the timer doesn't stop...

So what am i doing wrong?

I know there have been other questions like this but, i am still fairly new to java and i do not understand the answers given.

Thank you

The problem is that you are creating a new Timer every time waitReminderList is called. Any previous running Timer objects will not be stopped. Since you want a single Timer move the reference outside the method, eg at class level.

Don't keep creating a new Timer in your waitReminderList() method. You should define the Timer as a class variable.

Then you just stop/start it as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM