I want to display a JFrame
when a user move the mouse pointer inside over a certain area of a JPanel
with a little delay. I show the JFrame
by attaching a MouseAdapter
to the JPanel
and overriding the MouseMove
method.
addMouseListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
Point p= e.getLocationOnScreen();
//check if Point p is within the boundaries of a rectangle.
//show a JFrame
}
});
To obtain the delay I think that I should use something like a Thread
by using sleep
, with the condition that it must be interrupted if the mouse is moved out of the boundaries, but I'm not sure that this is the best approach. Currently, I only see on SO questions related to JavaScript. What's the best way to do it in Java?
You can use the mouseEntered
and mouseExited
events from the MouseAdapter
class.
You can set a timer on the mouseEntered
method and check if the time spent on the object is >=
the designated time in the mouseExited
method and if so perform the action.
For the scenario of mouse left at the same point, you can use the Timer
with a delay of how many ever seconds you want and setup a handler at mouseExited
to stop the timer if the pointer is exited before the designated time.
Maybe a good solution is by using java.util.Timer
.
addMouseListener(new MouseAdapter() {
private int delay = 1000;//1 second
private Timer timer = null;
private int startTime =0;
@Override
public void mouseMoved(MouseEvent e) {
Point p= e.getLocationOnScreen();
boolean pointInArea=false;
//check if Point p is within the boundaries of a rectangle.
if(pointInArea){
//A JFrame is queued to be shown
if(System.currentTimeMillis()-startTime>delay){
//A JFrame has been already shown, then show a new one
startTime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new TimerTask(){
@Override
public void run() {
//LAUNCH JFrame
}
}, delay);
}
}
else (!pointInArea && timer != null){
timer.cancel();
timer = null;
}
}
});
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.