Search code examples
javajavafxdesktop-application

JavaFX - auto hide window on mouse over


Goal

I need to create a javafx stage which hides when mouse move over it, but show when mouse is not over my stage. My stage should,

  • Hide when I bring mouse pointer on to it
  • Show when mouse pointer is on any place of screen other than on my stage
  • Allow to click/focus through it, when it is hidden

Problem

Although it seems like a very easy task, I cannot figure out how to do it correctly. Yes, we can easily implement the logic to hide the stage (using mouse event listeners). But, when showing the hidden stage, it seems so difficult as the hidden stage cannot listen to any mouse event.

  • Can we implement this without low-level system-wide logic?
  • If so, how can we implement it? Can anyone suggest a good approach?
  • If we need to use low-level system-wide logic how can we do it while keeping platform independent support?

Solution

  • In JavaFX you can use the javafx.scene.robot.Robot to get the mouse pointer locations. Then the job will be very easy for you.

    As an example you could do something like this,

    Bounds interfaceBounds = ...;
    Robot robot = new Robot();
    

    An assume you have two functions for hide/show the interface.

    void hide() { ... }
    void show() { ... }
    

    Then you the following code in another thread (timer).

    Point2D urMouse = robot.getMousePosition();
    if( !interfaceBounds.contains( urMouse ) )
    {
        hide();
    }else{
        show();
    }