Summary

JTabbedPaneのタブが選択されている場合のフォーカスBorderをドットの囲み罫ではなく下線に変更します。

Source Code Examples

class UnderlineFocusTabbedPane extends JTabbedPane {
  private static final Color ALPHA_ZERO = new Color(0x0, true);
  private static final Color SELECTION_COLOR = new Color(0x00_AA_FF);

  protected UnderlineFocusTabbedPane() {
    super();
  }

  @Override public void updateUI() {
    UIManager.put("TabbedPane.focus", new Color(0x0, true));
    super.updateUI();
    addChangeListener(e -> updateTabBorder((JTabbedPane) e.getSource()));
  }

  private static void updateTabBorder(JTabbedPane tabs) {
    int tabCount = tabs.getTabCount();
    if (tabCount > 0) {
      int selectedIndex = tabs.getSelectedIndex();
      for (int i = 0; i < tabCount; i++) {
        Component c = tabs.getTabComponentAt(i);
        if (c instanceof JComponent) {
          Color color = i == selectedIndex ? SELECTION_COLOR : ALPHA_ZERO;
          Border b = BorderFactory.createMatteBorder(0, 0, 3, 0, color);
          ((JComponent) c).setBorder(b);
        }
      }
    }
  }

  @Override public void insertTab(
      String title, Icon icon, Component component, String tip, int index) {
    super.insertTab(title, icon, component, tip, index);
    JLabel label = new JLabel(title, icon, CENTER);
    setTabComponentAt(index, label);
  }
}
View in GitHub: Java, Kotlin

Description

Reference

Comment