• title: UIManagerで使用するFontを統一 tags: [UIManager, Font] author: aterai pubdate: 2003-10-27 description: Swingの各種コンポーネントで使用する全てのフォントを一気に変更します。

概要

Swingの各種コンポーネントで使用する全てのフォントを一気に変更します。

サンプルコード

private void updateFont(final Font font) {
  FontUIResource fontUIResource = new FontUIResource(font);
  for (Map.Entry<?, ?> entry: UIManager.getDefaults().entrySet()) {
    if (entry.getKey().toString().toLowerCase().endsWith("font")) {
      UIManager.put(entry.getKey(), fontUIResource);
    }
  }
  //SwingUtilities.updateComponentTreeUI(this);
  recursiveUpdateUI(this);
  frame.pack();
}
private void recursiveUpdateUI(JComponent p) {
  for (Component c: p.getComponents()) {
    if (c instanceof JToolBar) {
      continue;
    } else if (c instanceof JComponent) {
      JComponent jc = (JComponent) c;
      jc.updateUI();
      if (jc.getComponentCount() > 0) {
        recursiveUpdateUI(jc);
      }
    }
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、ツールバーのボタンでコンポーネントが使用するフォントを切り替えています。ただしツールバーだけは、UIupdate(フォントの変更)を除外しています。

全部のコンポーネントではなく、例えばテーブルのフォントだけ変更したい場合は以下のように設定します。

UIManager.put("Table.font", new FontUIResource(font));

UIManagerから、UIDefaultsのキー一覧を作るなどして、いろいろ検索してみてください。

//キー一覧の作成例
import java.util.Map;
import javax.swing.UIManager;
class Test {
  public static void main(String[] args) {
    //for (Object o:UIManager.getDefaults().keySet()) //は、うまくいかない?
    //for (Object o:UIManager.getLookAndFeelDefaults().keySet())
    for (Map.Entry<?, ?> entry: UIManager.getDefaults().entrySet())
      System.out.println(entry.getKey());
  }
}

Metalで使用されているフォントが気に入らないだけなら、システムLookAndFeelを使用するか、Metalでボールドフォントを無効にするなどの方法があります。

  • MetalLookAndFeelではなく、SystemLookAndFeelを使用する
try {
  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
  e.printStackTrace();
}
UIManager.put("swing.boldMetal", Boolean.FALSE);

combo.setFont(font);
//以下回避方法
combo.setPrototypeDisplayValue(null); //null:default?
//or combo.firePropertyChange("prototypeDisplayValue",0,1); //0,1:dummy

特定のインスタンスだけ、LookAndFeelなどを変更しても常に独自のフォントを設定したい場合、JComponent#updateUI()をオーバーライドして設定する方法もあります。

JLabel label = new JLabel() {
  @Override public void updateUI() {
    super.updateUI();
    setFont(...);
  }
};

参考リンク

コメント