问题
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