Java: remove margin / padding on a JTabbedPane

florian picture florian · Mar 3, 2011 · Viewed 12.3k times · Source

I'd like to know how to remove the margins between my JtabbedPane and my JFrame content pane and between my JTabbedPane and its internal JPanel. I circled the margins I want to remove. the green line is here to show the gap between the jpanel inside the jtabbedpane.

I tried to look at some method named setMargin but it doesn't exist on a JTabbedPane. I also checked the Hgap and Vgap (both = 0) on the different layout (root content pane, my jpanel, etc).

So any suggestions are welcome. Thanks.

The image is here.

I can't post images yet.

Answer

Tim Boudreau picture Tim Boudreau · Mar 3, 2011

It is up to the look and feel to decide how much space is around components inside a tabbed pane - generally it will do this based on whatever is the default for your desktop. JTabbedPane does not have methods for setting the insets around internal components.

You can set this globally for all tabbed panes (caveat: Works on MetalLookAndFeel, will probably work for Windows L&F as well, probably won't work for GTK or Nimbus look and feel which are not based on BasicLookAndFeel). This will change the appearance of all tabbed panes in the VM:

UIManager.getDefaults().put("TabbedPane.contentBorderInsets", new Insets(0,0,0,0));
UIManager.getDefaults().put("TabbedPane.tabsOverlapBorder", true);

You probably also want to make sure your JTabbedPane has an EmptyBorder(0,0,0,0) and so do the components you put in it.

If this doesn't work on your target desktop, the alternatives are

  • if you don't care about your tabbed panes looking different from native application tabbed panes, the (unpleasant) alternative is to write your own TabbedPaneUI
  • set the UI delegate for the single JTabbedPane you want to look like this to MetalTabbedPaneUI or some other UI delegate that does respond to these properties