JavaFX – How to change or hide mouse cursor in the entire application (WebView + Scene)

JavaFX – How to change or hide mouse cursor in the entire application (WebView + Scene)

In this post, I present the steps that allow you to hide or change the mouse cursor shape in the entire JavaFX application. You will find solutions for the problems that I have encountered so far by implementing the requirement. In particular, you will learn how you can detect and porform the change of the cursor in the WebView control.

Agenda
  1. Changing the mouse cursor in any JavaFX control
  2. Changing the mouse cursor in the WebView control


Changing the mouse cursor in any JavaFX control

Let’s consider the HelloWorld JavaFX application shown below. It consists of a class called Main, which is also a acontroller for sample.fxml form. In the class you can find handles for Pane and WebView controls, as well as the initialize method, which is executed as soon as the form is ready to initialize.

 

Solution A: Changing mouse pointer in the entire application
Changing the cursor for a scene comes down to calling the setCursor() method on it. Below is an example of hiding the cursor for the whole scene. All elements except the WebView control will inherit the cursor. I described the reason and the solution in the next section.

 

Solution B: Changing the mouse pointer in any JavaFX control
The change of the cursor for any control is done in the same way as it was shown for the scene- that is by calling the setCursor method on the control. The following example shows how to change the mouse pointer into open hand shape.

 

Changing the mouse cursor in the WebView control


The WebView component plays the role of a web browser in JavaFX. Therefore, its main task is to display HTML pages. In the case of the WebView control, the problem of hiding or changing the cursor becomes a bit more complicated, because the mouse cursor changes quite often and additionally calling the setCursor method on the WebView component does not seem to be effective.

However, this is not entirely true. In fact, by calling the myWebView.setCursor(Cursor.NONE) method, we hide the cursor, but the movement of the mouse causes that it adapts to the content of the page being viewed, changing to the appropriate one (eg pointing to the link).

Solution C: Changing the mouse cursor in the WebView component
The solution to the problem is to add a listener to the WebView’s cursor attribute and then, as soon as we detect the change, we immediately set it back to the target cursor. In practice, it looks like below:

 

If you think this post is valuable, please leave me +1 or just share it. This action will allow me to reach a wider audience. Thank You in advance.

 

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu