Java Swing How to - Handle the height of the tab title in JTabbedPane








Question

We would like to know how to handle the height of the tab title in JTabbedPane.

Answer

import java.awt.Graphics;
import java.awt.Rectangle;
//w w  w. j  ava 2 s .  c  om
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;

public class Main {
  public JComponent makeUI() {
    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP,
        JTabbedPane.SCROLL_TAB_LAYOUT);
    tabbedPane.setUI(new javax.swing.plaf.basic.BasicTabbedPaneUI() {
      @Override
      protected int calculateTabHeight(int tabPlacement, int tabIndex,
          int fontHeight) {
        return 32;
      }

      @Override
      protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects,
          int tabIndex, Rectangle iconRect, Rectangle textRect) {
        if (tabIndex == 0) {
          rects[tabIndex].height = 30 + 1;
          rects[tabIndex].y = 32 - rects[tabIndex].height + 1;
        } else if (tabIndex == 1) {
          rects[tabIndex].height = 26 + 1;
          rects[tabIndex].y = 32 - rects[tabIndex].height + 1;
        }
        super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect);
      }
    });
    tabbedPane.addTab("000", new JLabel("ok"));
    tabbedPane.addTab("111", new JScrollPane(new JTable()));
    tabbedPane.addTab("222", new JSplitPane());

    return tabbedPane;
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new Main().makeUI());
    frame.setSize(320, 240);
    frame.setVisible(true);
  }
}