17slim
17slim

Reputation: 1233

Use mouse to scroll through tabs in JTabbedPane

I have a JTabbedPane in a scroll tab layout, so that all the tabs sit nicely on one row. Is there a way to allow the user to scroll through them with the mouse wheel, or is the only way to navigate the JTabbedPane.SCROLL_TAB_LAYOUT with the keyboard's and GUI's arrows and by clicking the tabs?

Upvotes: 4

Views: 613

Answers (1)

17slim
17slim

Reputation: 1233

I did find an answer to this, after digging around Eclipse's autocomplete: use a MouseWheelListener for the JTabbedPane:

JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
tabbedPane.addMouseWheelListener(new MouseWheelListener() {
    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        JTabbedPane pane = (JTabbedPane) e.getSource();
        int units = e.getWheelRotation();
        int oldIndex = pane.getSelectedIndex();
        int newIndex = oldIndex + units;
        if (newIndex < 0)
            pane.setSelectedIndex(0);
        else if (newIndex >= pane.getTabCount())
            pane.setSelectedIndex(pane.getTabCount() - 1);
        else
            pane.setSelectedIndex(newIndex);
    }
});

This both allows for mouse scrolling over the tabs, and respects the index bounds of the JTabbedPane.

If anyone has a better answer, I'd be happy to accept!

Upvotes: 9

Related Questions