简体   繁体   中英

Waiting between event listeners java

My problem:

I've got two events listeners attached to a JLabel and a variable A

boolean A = false;
public void mouseEntered(MouseEvent evt) { ... }
public void mouseExited(MouseEvent evt) { ... }

What I would like to do is the following: when mouseExited is triggered wait during X milliseconds for catching some changes (if happened) in the A variable due to some code into the mouseEntered event listener.

I already tried with Timer but doesn't work --> I can't catch the new value of variable A during the wait period. I can only catch it after Timer is out.

Any ideas to implement this?

I tried this,

label.addMouseListener(new MouseAdapter() {
    java.util.Timer t;

    @Override
    public void mouseEntered(MouseEvent evt) {
         // Test Condition
         if(condition) {
             // do something
         } else {
             t.cancel();
             t.purge();
         }
    }

    @Override
    public void mouseExited(MouseEvent e) {
        t = new java.util.Timer();
        t.schedule(new TimerTask() {
            @Override
             public void run() {
                 // do something
                 t.cancel();
                 t.purge();
             }
        }, 1*1000);
    }

Steps of events:

1) mouseExited is triggered -> wait for 1 second
2) During this time, if mouseEntered is triggered (condition not verified in mouseEntered) it should ended the scheduled task but instead it throws back a Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

How is it possible to end this scheduled task if mouseEntered is triggered during tis time?

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