Java: remove margin / padding on a JTabbedPane

2019-02-17 22:12发布

问题:

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.

.

I can't post images yet.

回答1:

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


回答2:

I just struck the same problem, and nothing anyone else said seemed to be a complete solution, so I came up with this:

    import javax.swing.plaf.basic.BasicTabbedPaneUI;

    tabbedPane.setUI(new BasicTabbedPaneUI() {
        private final Insets borderInsets = new Insets(0, 0, 0, 0);
        @Override
        protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) {
        }
        @Override
        protected Insets getContentBorderInsets(int tabPlacement) {
            return borderInsets;
        }
    });

It works the same without overriding the paintContentBorder method, however doing so probably makes the UI slightly more efficient during resizes or similar, as the standard one seems to delegate out to a number of other methods.

Tested on Oracle Java 6 u43 for Linux in WindowMaker, Mac OS X 10.6.7 with Mac Java 6 u37 and Windows 7 with Java 7 u07, hopefully this helps someone :-)



回答3:

Margins are added by setting borders on UI elements. Have a look at the settings of the border of your JTabbedPane.