Thursday, September 17, 2015

Scrolling vs. Navigating in JTabbedPane

It is possible to programatically move between the tabs of a JTabbedPane:

There are two mechanisms: Navigating and scrolling. Their difference is that navigation changes the selected tab while scrolling shifts the view but does not change the selected tab.

When we navigate to the next tab, it will look like this (notice that the selected tab has changed from 1 to 2):

When we scroll forward, it will look like this (notice that although the view has shifted to right, the selected tab is still 2):

The code for navigation is as follows:
// jtp is a JTabbedPane instance
Action action = jtp.getActionMap().get("navigateNext"); //To go back, use “navigatePrevious”
action.actionPerformed(new ActionEvent(jtp, ActionEvent.ACTION_PERFORMED, ""));

The code for scrolling is as follows:
Action action = jtp.getActionMap().get("scrollTabsForwardAction"); //To go back, use “scrollTabsBackwardAction”
action.actionPerformed(new ActionEvent(jtp, ActionEvent.ACTION_PERFORMED, ""));

JTabbed frame has a problem: When all the tabs do not fit to the view and a tab that's not in the view is marked as selected, you have to scroll to bring the selected tab to the front view. Below is a small method that can solve this problem by scrolling back and forth. Note that it has to be called after its containing frame is made visible (with setVisible(true)) or it won't have any effect.
/**
* This method should be called after the frame is made visible.
* It scrolls back and forth to bring the selected tab to front view.
*/
private static void bringSelectedToFront(JTabbedPane jtp) {
    for (int i = 0; i < jtp.getTabCount() - 1; i++) {
        Action action = jtp.getActionMap().get("scrollTabsBackwardAction");
        action.actionPerformed(new ActionEvent(jtp, ActionEvent.ACTION_PERFORMED, ""));
    }
    for (int i = 0; i < jtp.getTabCount() - 1; i++) {
        Action action = jtp.getActionMap().get("scrollTabsForwardAction");
        action.actionPerformed(new ActionEvent(jtp, ActionEvent.ACTION_PERFORMED, ""));
    }
}
The effect of this method (for the case when the fifth tab was marked as selected):

The action key strings for JTabbedPane are defined in BasicTabbedPaneUI (in its private class Actions). For more information, see How to Use Actions.

1 comment:

Danilo Sekulic said...

Thank you very much. It's nicely explained and it helped me with problem of scrolling tabs.