Search code examples
javaswinguser-interfacejtabbedpane

Swing JTabbedPane how to set scroll width?


I use the following code to create a JTabbedPane

new JTabbedPane(JTabbedPane.LEFT,JTabbedPane.SCROLL_TAB_LAYOUT);

It results in a scroll that is smaller in width than the tab selection area

enter image description here

How can I make the scroll width wider so that it fits the tab selection area?


Solution

  • You can extend BasicTabbedPaneUI and implement you own button in createScrollButton() providing new preferred size. It looks like BasicTabbedPaneUI has its own private implementation for these buttons - ScrollableTabButton. You can create something similar, like the following:

    public class ExtendedTabbedPaneUI extends BasicTabbedPaneUI {
    
        @Override
        protected JButton createScrollButton(int direction) {
             if (direction != SOUTH && direction != NORTH && direction != EAST &&
                                       direction != WEST) {
                 throw new IllegalArgumentException("Direction must be one of: " +
                                                    "SOUTH, NORTH, EAST or WEST");
             }
    
             //return new ScrollableTabButton(direction);
    
             return new BasicArrowButton(direction,
                UIManager.getColor("TabbedPane.selected"),
                UIManager.getColor("TabbedPane.shadow"),
                UIManager.getColor("TabbedPane.darkShadow"),
                UIManager.getColor("TabbedPane.highlight")) {
    
                @Override
                public Dimension getPreferredSize() {
                    int maxWidth = calculateMaxTabWidth(JTabbedPane.LEFT);
                    return new Dimension(maxWidth, super.getPreferredSize().height);
                }
            };
        }
    }
    

    And to setup new UI:

    tabbedPane.setUI(new ExtendedTabbedPaneUI());