我正在尝试创建一个Swing面板,其元素的字体大小与swing应用程序的其余部分不同.最初,使用setFont几个组件并没有造成任何问题.现在我有几个组件(及其所有子组件),因此这个解决方案是不切实际的.
我搜索过有关更改swing组件的默认UI属性的信息.我发现的主要是使用UIManager,它可以全局更改属性.这对我不起作用,因为我想保留所有其他面板的当前字体设置.
目前(因为我不想在没有首先尝试的情况下发帖),我有一个这样的算法:
public static void fixFont(Container c) {
c.setFont(c.getFont().deriveFont(10.0f));
Component[] comp = c.getComponents();
for (int i=0;i<comp.length;++i) {
if (comp[i] instanceof Container) {
fixFont((Container) comp[i]);
} else {
comp[i].setFont(comp[i].getFont().deriveFont(10.0f));
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:
问题:是否有其他方法可以更改Swing面板及其所有组件,元素等的字体属性(即面板中的所有内容)?
谢谢你的想法
你可以使用这个技巧:
import java.awt.*;
public class FrameTest {
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());
UIManager.put(key, new FontUIResource(font));
}
}
}
public static void main(String[] args) throws InterruptedException {
setUIFont(new FontUIResource(new Font("Arial", 0, 20)));
JFrame f = new JFrame("Demo");
f.getContentPane().setLayout(new BorderLayout());
JPanel p = new JPanel();
p.add(new JLabel("hello"));
p.setBorder(BorderFactory.createTitledBorder("Test Title"));
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 300);
f.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
生产:

| 归档时间: |
|
| 查看次数: |
15759 次 |
| 最近记录: |