• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTabbedPaneの選択文字色を変更
#navi(../)
RIGHT:Posted by [[terai]] at 2004-02-09
*JTabbedPaneの選択文字色を変更 [#q40bd72b]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-02-09~
更新日:&lastmod;

#contents

**概要 [#qaaf3ed4]
JTabbedPaneで、選択されたタブの文字色を変更します。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#g98608e3]
#code{{
tab.addChangeListener(new ChangeListener() {
  public void stateChanged(ChangeEvent e) {
    JTabbedPane jtab = (JTabbedPane)e.getSource();
    jtab.setVisible(false);
    int sindex = jtab.getSelectedIndex();
    String str = jtab.getTitleAt(sindex);
    for(int i=0;i<jtab.getTabCount();i++) {
      if(i==sindex && "タイトル1".equals(str)) {
        //jtab.setBackgroundAt(i, Color.GREEN);
        jtab.setForegroundAt(i, Color.GREEN);
      }else if(i==sindex) {
        Color sc = (sindex%2==0)?Color.RED:Color.BLUE;
        //jtab.setBackgroundAt(i, sc);
        jtab.setForegroundAt(i, sc);
      }else{
        //jtab.setBackgroundAt(i, null);
        jtab.setForegroundAt(i, Color.BLACK);
      }
    }
    jtab.setVisible(true);
  }
});
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#a0f82c36]
新たにChangeListenerを追加し、条件によってタブの文字色を変更しています。

背景色も変更したかったのですが、Look and Feelなどによってはうまくいかないようです。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());
  }
  final JFrame frame = new JFrame("@title@");
//......
}}

**参考リンク [#l67a03ff]
-[[TabColorExample>http://www.crionics.com/products/opensource/faq/swing_ex/JTabbedPaneExamples1.html]]
-[[JTabbedPaneのタブ文字列をハイライト>Swing/TabTitleHighlight]]

**コメント [#y2155bad]
#comment