2022-07-07 (木) 14:20:26
  • 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

概要

JTabbedPaneで、選択されたタブの文字色を変更します。
http://terai.xrea.jp/swing/colortab/screenshot.png

サンプルコード

#spanend
#spanadd
tabbedPane.addChangeListener(e -> {
#spanend
  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);
    }
  }
#spanadd
});
#spanend
#spanadd
View in GitHub: Java, Kotlin
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++){

        //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);
  }
});

解説

JTabbedPaneChangeListenerを追加し、条件によってタブの文字色を変更しています。
  • タブ文字色: JTabbedPane#setForegroundAt(Color)
  • タブ背景色: JTabbedPane#setBackgroundAt(Color)
    • Look and Feelに依存する(JDK 1.7.0からドキュメントに追記された)
    • Windows XPでタブの背景色を変更したい場合は、以下のようにSystem.setProperty("swing.noxp", "true")と設定する必要がある
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@");
  • TabColorExample
    #spanend
    #spanadd
    public static void createAndShowGUI() {
    #spanend
      System.setProperty("swing.noxp", "true");
      try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      } catch (Exception e) {
        throw new InternalError(e.toString());
      }
      JFrame frame = new JFrame("@title@");
    #spanadd
    // ...
    #spanend
    #spanadd
    

参考リンク

コメント