我用过Romain Hippeau's answer 。为了在应用程序首次构建时设置默认字体。
public static void setUIFont(javax.swing.plaf.FontUIResource f) {
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource)
UIManager.put(key, f);
}
然后调用它:
setUIFont(new javax.swing.plaf.FontUIResource("Sans", Font.PLAIN, 24));
但是,当新文本写入 swing 应用程序时:即
JTextArea textArea = new JTextArea();
onSomeEventHappening(){
textArea.setText("Hello world");
}
Hello world 以标准 swing 字体显示,而我的所有其他元素仍保留我希望所有内容保留的字体。有什么方法可以确保添加到应用程序中的所有新文本都不会更改其字体。
上面显示了一个示例,单词“FOOTBALL”
已写入其组合框中,因此以 Swing 的正常字体显示,而我的按钮“生成一个链接”
以我设置的字体显示。
下面是一个复制粘贴的例子,如果你点击按钮,尽管设置了上面的字体,标签仍然是Swings原来的样式:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class test extends JFrame {
private static final int WIDTH = 1000;
private static final int HEIGHT = 700;
private JTextArea textArea = new JTextArea();
public static void setUIFont(javax.swing.plaf.FontUIResource f) {
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource)
UIManager.put(key, f);
}
}
public test(){
initialize();
}
final ActionListener buttonClick = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText("new Text");
}
};
public void initialize(){
new JFrame();
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1,2));
setUIFont(new javax.swing.plaf.FontUIResource("Sans", Font.PLAIN, 24));
JButton button = new JButton("test");
button.addActionListener(buttonClick);
this.add(button);
this.add(textArea);
setVisible(true);
}
public static void main(String[] args){
test test1 = new test();
}
}
最佳答案
private JTextArea textArea = new JTextArea();
...
setUIFont(new javax.swing.plaf.FontUIResource("Sans", Font.PLAIN, 24));
...
JButton button = new JButton("test");
在更改字体之前您已经创建了 JTextArea。
Swing 组件在创建时获取其 UI 属性。
因此,您需要在设置字体后创建 JTextArea,与 JButton 的操作相同。
注意:如果在创建组件后更改属性,则需要重置属性。
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
阅读 Swing 教程中关于 How to Set the Look and Feel After Startup 的部分了解更多信息。
关于java - 即使绘制新文本,也设置一次 swing 应用程序的默认字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51194267/