概要
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 all解説
上記のサンプルでは、ツールバーのボタンでコンポーネントが使用するフォントを切り替えています。ただしツールバーだけは、UI
のupdate
(フォントの変更)を除外しています。
全部のコンポーネントではなく、例えばテーブルのフォントだけ変更したい場合は以下のように設定します。
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();
}
MetalLookAndFeel
で、bold fonts
を無効にする場合
UIManager.put("swing.boldMetal", Boolean.FALSE);
JComboBox#setFont
をしても、JComboBox
自体のサイズが更新されない
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(...);
}
};