Use mouse to scroll through tabs in JTabbedPane

不羁的心 提交于 2020-01-14 03:10:09

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/38463047/use-mouse-to-scroll-through-tabs-in-jtabbedpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!