How to make a libGDX scrollpane scroll without clicking on it first

Viewed 282

My scrollpane works fine, but in order for it to scroll, it first needs to be clicked on. Even if the libGDX application itself is focused, it will not scroll until I click on it.

I'm not trying to make it scroll automatically. I just think that when a user has an application focused, and that user interacts with an UI element that can scroll, they would expect it to scroll by simply using the scroll wheel on their mouse, without having to click the element again.

1 Answers

You can add a listener to change the focus when the mouse enters or exits the ScrollPane. You can even make that into a custom subclass so you don't have to duplicate it everywhere:

public class AutoFocusScrollPane extends ScrollPane {

    public AutoFocusScrollPane() {
        super(null);
        addListener(new InputListener() {
            public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
                getStage().setScrollFocus(AutoFocusScrollPane.this);
            }

            public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
                getStage().setScrollFocus(null);
            }
        });
    }
}

This should make the ScrollPane scrollable as soon as soon as the mouse touches the actor and it should stop being scrollable when the mouse leaves it.

Related