3

I have a JTabbed pane, which has a varying number of tabs. When the number of tabs is greater than 4, I get extra spacing/padding at the bottom of each tab panel. The picture below shows this (on the left you see the extra spacing, on the right you see no extra spacing).

enter image description here

Here is the exact code I used to get those pictures:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class DialogTest {

    public static void main(String[] args) {
        new DialogTest();
    }

    public DialogTest() {
        JDialog dialog = new MyDialog();
        dialog.pack();
        dialog.setVisible(true);
    }

    class MyDialog extends JDialog {

        public MyDialog() {
            super(null, ModalityType.APPLICATION_MODAL);

            final JTabbedPane tabs = new JTabbedPane();
            final int numTabs = Integer.parseInt(JOptionPane.showInputDialog("Number of tabs:"));

            setPreferredSize(new Dimension(400, 200));

            for (int i = 1; i <= numTabs; i++) {
                tabs.addTab("Tab"+i, new MyPanel(i));
            }

            setLayout(new BorderLayout());
            add(tabs, BorderLayout.NORTH);
        }
    }

    class MyPanel extends JPanel {
        public MyPanel(int text) {
            final JLabel label = new JLabel("THIS IS A PANEL" + text);
            label.setFont(label.getFont().deriveFont(18f));
            label.setBackground(Color.cyan);
            label.setOpaque(true);

            add(label);
            setBackground(Color.red);
        }   
    }
}

I've tried numerous things including many different layout managers. I can't for the life of me get rid of that extra spacing. Any help would be great.

Smitty
  • 403
  • 2
  • 11

1 Answers1

2
final JTabbedPane tabs = new JTabbedPane();
tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); // ADD THIS!

The reason the other example behaves as it does is that the pane wraps the tabs to the next line & presumes that once we have gone beyond as many tabs as it might naturally display in a single line, it must increase the preferred size to include that extra line of tabs.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    You're welcome. Good work on posting an SSCCE of the problem. That made it very easy to run it, see the problem and test my solution. :) – Andrew Thompson Oct 02 '13 at 18:04
  • This forces the tabs to form a single row, though. Is there a way to have more than one row of tabs, while avoiding the extra spacing/padding at the bottom? – Guillaume F. Aug 22 '19 at 09:26
  • @GuillaumeF. *"Is there a way to.."* Good question (which deserves its own question thread, if not already asked & answered hereabouts). – Andrew Thompson Aug 22 '19 at 09:59