JTabbedPaneのタブが選択されている場合のフォーカスBorderを下線に変更する
Total: 2078, Today: 1, Yesterday: 3
Posted by aterai at
Last-modified:
Summary
JTabbedPaneのタブが選択されている場合のフォーカスBorderをドットの囲み罫ではなく下線に変更します。
Screenshot

Advertisement
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, KotlinDescription
- デフォルトのフォーカス
Borderを非表示にし、代わりに選択されたタブのタブタイトルに設定したJLabelにMatteBorderで作成した下線を適用 JTabbedPaneにChangeListenerを追加してタブの切り替えイベントを取得してMatteBorderを切り替えJTabbedPane#setFocusable(false)などでフォーカス自体を不可にする方法もあるが、カーソルキーでの選択移動も不可になるのでこのサンプルではBasicTabbedPaneUI#paintFocusIndicator(...)をオーバーライドしてデフォルトのフォーカスBorderを非表示化- JTabbedPaneのタブ描画をフラットデザイン風に変更する
UIManager.put("TabbedPane.focus", new ColorUIResource(new Color(0x0, true)));でフォーカスBorderを非表示にする方法もある
Reference
- JTabbedPaneの選択文字色を変更
- JTabbedPaneのタブ描画をフラットデザイン風に変更する
- CardLayoutで作成したJTabbedPane風コンポーネントのタブエリアに水平JScrollBarを表示する