简体   繁体   中英

MouseListener delay a bit mouseEntered

I have a JLabel and I use a MouseListener on it. I use the known code:

jl.addMouseListener(new MouseAdapter() {
    public void mouseEntered(MouseEvent me) {
        System.out.println("Entered")
    }
});

And the text Entered is printed when I enter the mouse on the JLabel . Everything is fine but I'd like to exist a bit of delay (like 1-2 seconds) by the time I enter the cursor on the JLabel and then the text to be printed. How can I accomplish this? Thanks a lot

Given the single threaded nature of the Swing API and the fact that the API is not thread safe, I'd recommend using a Swing Timer to inject a small delay between the event and your operation, for example...

Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent evt) {
        //...
    }
});
timer.setRepeats(false); // So you are notified only once per mouseEnter event

jl.addMouseListener(new MouseAdapter() {
    public void mouseEntered(MouseEvent me) {
        timer.restart();
    }
});

This example will delay the calling of the ActionListener by 1 second every time the mouse triggers the mouseEntered event. Note though, if the user exits and enters the label before the delay expires, it will be reset back to the start.

If you want some event to trigger 1 second after ANY mouseEnter event, then you could simply create a new Swing Timer on each mouseEnter event instead.

Take a look at Concurrency in Swing and How to use Swing Timers for more details

Use a ScheduledExecutorService

Somewhere in your program you need to create one:

final ScheduledExecutorService svc = Executors.newScheduledThreadPool(1);

Then in your mouse listener schedule a task:

jl.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseEntered(MouseEvent me) {
        svc.schedule(new Runnable() {
            @Override
            public void run() { System.out.println("Entered"); }
        }, 2, TimeUnit.SECONDS); 
    }
});

I would separate some of the functionality out in to methods that are called by the anonymous inner classes. Nesting the anonymous inner classes like this can quickly lead to hard-to-read and hard-to-maintain code.

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