Skip to content

CursorProvider

fishstiz edited this page Feb 5, 2025 · 6 revisions

The CursorProvider interface provides an alternative to the element registration system. Implementing elements can directly declare which cursor type to be applied when it is being hovered by the mouse using CursorProvider#getCursorType(mouseX, mouseY).

Note: The element must be an instance of net.minecraft.gui.Element. It must either be the current screen itself or be accessible from the current screen or from its parent element using the ParentElement#children() method.

Any container or nested container must be an instance of net.minecraft.gui.ParentElement and accessible via the ParentElement#children() method. This accessibility must be maintained through the entire element hierarchy, starting from the current screen down to the deepest nested parent element.

Implementing CursorProvider

  • For Required Dependencies: Implement CursorProvider directly in your element class.

    public class MyButton extends ClickableWidget implements CursorProvider {
        // ... your other methods
    
        @Override
        public CursorType getCursorType(double mouseX, double mouseY) {
            return CursorType.POINTER;
        }
    }
  • For Optional Dependencies: You may create a subclass of your element that implements CursorProvider. In your element factory method, check if minecraft-cursor is loaded before using the subclass. This allows you to safely integrate Minecraft Cursor as an optional dependency.

    MyButton:

    public class MyButton extends ClickableWidget {
        // ... your methods
    }

    MyButtonCursorProvider:

    public class MyButtonCursorProvider extends MyButton implements CursorProvider {
        @Override 
        public CursorType getCursorType(double mouseX, double mouseY) {
            return CursorType.POINTER;
        }
    }

    MyButton factory:

    if (FabricLoader.getInstance().isModLoaded("minecraft-cursor")) {
        return new MyButtonCursorProvider();
    } else {
        return new MyButton();
    }

Implement CursorProvider to your custom Screen

CursorProvider can also be implemented in custom screens because Screen is an Element. The method CursorProvider#getCursorType(mouseX, mouseY) will be invoked after each render call—assuming your custom Screen behaves like a typical Screen (it is still only invoked when Element#isMouseOver(mouseX, mouseY) returns true).

This approach offers greater control over the cursor type at the screen level, allowing you to manage cursor behavior based on the state of your elements or other custom conditions.

It also helps you avoid the complexity of dealing with the element/parent element hierarchy, making it easier to handle the cursor type of nested elements.

Clone this wiki locally