Skip to main content

Change the Tab Size of JTabbedPane

Posted by xuanyun on January 27, 2009 at 4:17 AM PST

The JTabbedPane class has not provided an API to set the tab size, but sometimes
we do need this, we can find some ways to work arround.

First of all I create a JTabbedPane component with four tabs.

final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab1", new JLabel("Text Component 1"));
tabbedPane.addTab("Tab2", new JLabel("Text Component 2"));
tabbedPane.addTab("Tab3", new JLabel("Text Component 3"));
tabbedPane.addTab("Tab4", new JLabel("Text Component 4"));

Add this component to a JFrame and show it:

origin.png

I think the tabs are too small, I can use a one pixel width icon (1X32 pixels)
to force the tab become bigger:

tabbedPane.setIconAt(0, new ImageIcon("1x32.png"));

Now the tabs changed their heights:

img_pad.png

But we can not change the tab width by using icon. Fortunately the tab text
support HTML tags, we can use HTML to achieve our mission, here is how:

tabbedPane.addTab("<html><body leftmargin=15 topmargin=8 marginwidth=15 marginheight=5>Tab1</body></html>", new JLabel("Text Component 1"));
tabbedPane.addTab("<html><body leftmargin=15 topmargin=8 marginwidth=15 marginheight=5>Tab2</body></html>", new JLabel("Text Component 2"));
tabbedPane.addTab("<html><body leftmargin=15 topmargin=8 marginwidth=15 marginheight=5>Tab3</body></html>", new JLabel("Text Component 3"));
tabbedPane.addTab("<html><body leftmargin=15 topmargin=8 marginwidth=15 marginheight=5>Tab4</body></html>", new JLabel("Text Component 4"));

Now we have four bigger tabs, it looks good:

html_margin.png

Related Topics >>