---
category: swing
folder: ColorTab
title: JTabbedPaneの選択文字色を変更
tags: [JTabbedPane, ChangeListener]
author: aterai
pubdate: 2004-02-09
description: JTabbedPaneで、選択されたタブの文字色を変更します。
image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTJo7nZnbI/AAAAAAAAAUs/6SU2JG2B0t0/s800/ColorTab.png
---
* Summary [#summary]
`JTabbedPane`で、選択されたタブの文字色を変更します。
#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTJo7nZnbI/AAAAAAAAAUs/6SU2JG2B0t0/s800/ColorTab.png)
* Source Code Examples [#sourcecode]
#code(link){{
tabbedPane.addChangeListener(e -> {
JTabbedPane tabs = (JTabbedPane) e.getSource();
int sindex = tabs.getSelectedIndex();
String str = tabs.getTitleAt(sindex);
for (int i = 0; i < tabs.getTabCount(); i++) {
if (i == sindex && tabs.getTitleAt(sindex).endsWith("1")) {
tabs.setForegroundAt(i, Color.GREEN);
} else if (i == sindex) {
Color sc = (sindex % 2 == 0) ? Color.RED : Color.BLUE;
tabs.setForegroundAt(i, sc);
} else {
tabs.setForegroundAt(i, Color.BLACK);
}
}
});
}}
* Description [#explanation]
* Description [#description]
`JTabbedPane`に`ChangeListener`を追加し、条件によってタブの文字色を変更しています。
- タブ文字色: `JTabbedPane#setForegroundAt(Color)`
-- `Look and Feel`に依存する(`JDK 1.7.0`からドキュメントに追記された)
-- `Synth(Nimbus)LookAndFeel`などでは`JTabbedPane#setForegroundAt(Color)`メソッドは無効
-- [https://bugs.openjdk.org/browse/JDK-6939001 Bug ID: 6939001 Nimbus: JTabbedPane setBackgroundAt and setForegroundAt have no effect]
- タブ背景色: `JTabbedPane#setBackgroundAt(Color)`
-- `Look and Feel`に依存する(`JDK 1.7.0`からドキュメントに追記された)
-- `Windows XP`でタブの背景色を変更したい場合は、以下のように`System.setProperty("swing.noxp", "true")`と設定する必要がある
#code{{
public static void createAndShowGUI() {
System.setProperty("swing.noxp", "true");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
throw new InternalError(e.toString());
}
JFrame frame = new JFrame("@title@");
// ...
}}
* Reference [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTabbedPane.html#setForegroundAt-int-java.awt.Color- JTabbedPane#setForegroundAt(Color) (Java Platform SE 8)]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTabbedPane.html#setBackgroundAt-int-java.awt.Color- JTabbedPane#setBackgroundAt(Color) (Java Platform SE 8)]
- [[JTabbedPaneのタブ文字列をハイライト>Swing/TabTitleHighlight]]
* Comment [#comment]
#comment
#comment