Swing/ColorTab のバックアップの現在との差分(No.2)
#navi(contents-page-name): No such page: ST
FrontPage
2022-07-07 (木) 14:20:26
概要
JTabbedPane
で、選択されたタブの文字色を変更します。
Screenshot
Advertisement
サンプルコード
#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, Kotlintab.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); } });
解説
JTabbedPane
にChangeListener
を追加し、条件によってタブの文字色を変更しています。
- タブ文字色:
JTabbedPane#setForegroundAt(Color)
-
Look and Feel
に依存する(JDK 1.7.0
からドキュメントに追記された) -
Synth(Nimbus)LookAndFeel
などではJTabbedPane#setForegroundAt(Color)
メソッドは無効 - 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")
と設定する必要がある
-
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
参考リンク
- JTabbedPane#setForegroundAt(Color) (Java Platform SE 8)
- JTabbedPane#setBackgroundAt(Color) (Java Platform SE 8)
- JTabbedPaneのタブ文字列をハイライト