【问题标题】:How to change fonts of all components [duplicate]如何更改所有组件的字体[重复]
【发布时间】:2015-08-09 09:00:52
【问题描述】:

如何更改我的 java 应用程序中显示的所有组件的字体?

我用 UIManager 试过了

UIManager.put("TextField.font",  new java.awt.Font("Arial Unicode MS", java.awt.Font.PLAIN, 11));
UIManager.put("Label.font",  new java.awt.Font("Arial Unicode MS", java.awt.Font.PLAIN, 11));
UIManager.put("ComboBox.font",  new java.awt.Font("Arial Unicode MS", java.awt.Font.PLAIN, 11))

奇怪的是,这改变了文本字段的字体,但不适用于 JLabels 或 JComboBoxes

然后我尝试通过遍历 UIManager 知道的所有键来设置字体:

public static void setUIFont(FontUIResource f) {
    Enumeration keys = UIManager.getDefaults().keys();
    while (keys.hasMoreElements()) {
        Object key = keys.nextElement();
        Object value = UIManager.get(key);
        if (value instanceof FontUIResource) {
            FontUIResource orig = (FontUIResource) value;
            Font font = new Font(f.getFontName(), orig.getStyle(), f.getSize());
            FontUIResource fontUIResource = new FontUIResource(font);
            UIManager.put(key, fontUIResource);
            UIManager.getDefaults().put(key, fontUIResource);
            UIManager.getLookAndFeel().getDefaults().put(key, fontUIResource);
        }
    }
}

这段代码根本不起作用。

我必须说我使用 Synthetica 作为 LookAndFeel...所以我不知道这会如何干扰我通过 UIManager 进行的手动设置。

【问题讨论】:

标签: java swing fonts uimanager


【解决方案1】:

我认为你可以从Roman 更新this answer 如下:

public static void setUIFont (java.awt.Font f){
    java.util.Enumeration keys = UIManager.getDefaults().keys();
    while (keys.hasMoreElements()) {
      Object key = keys.nextElement();
      Object value = UIManager.get (key);
      if (value != null && value instanceof java.awt.Font)
        UIManager.put (key, f);
      }
}

然后将它与您的Font 一起使用,如下所示:

setUIFont (new java.awt.Font("Arial Unicode MS", java.awt.Font.PLAIN, 11));

【讨论】:

  • "new java.awt.Font("Arial Unicode MS".." 要获得更好的跨平台支持,请使用逻辑字体(例如 Font.SANS_SERIF 而不是 "Arial Unicode MS")。
  • 同意...但我只是在原始问题中使用了Font...
  • 它没有用。我调试了代码并为每个组件编写了值,但 UI 仍然相同。 Synthetica 是否有可能忽略这些手动设置?
  • 这是来自here的复制粘贴答案,您只是稍微更改了名称和编号。
  • @user1803551 实际上我在我的一个应用程序中使用它,是的,我想我从那里拿走了它,因为我的支持仍然存在......问题出在哪里?
【解决方案2】:

您可以创建自己的组件,例如:

public class MyJButton extends JButton {

    public MyJButton(){
        setFont(FontClass.getBasicFont());
    }

}

public class MyJTextArea extends JTextArea {

    public MyJTextArea (){
        setFont(FontClass.getBasicFont());
    }

}
.
.
.

然后创建一个包含所有字体属性的类,例如:

public class FontClass(){

    private static final String BASIC_FONT_FACE = "Arial";

    private static final String BASIC_FONT_SIZE = 12;

    public static Font getBasicFont(){
        return new Font(BASIC_FONT_FACE, Font.PLAIN, BASIC_FONT_SIZE);
    }

}

我想这是原始的方式,但如果你想保存它可能会很好 您的数据库中的这些值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-13
    • 2018-06-27
    • 2015-09-22
    • 2015-10-15
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多