更改JPanel及其所有元素的字体大小 [英] Change font size of a JPanel and all its elements
问题描述
我正在尝试创建一个Swing面板,其元素的字体大小与swing应用程序的其余部分不同.最初,对两个组件使用 setFont
不会造成任何问题.现在我有几个组件(及其所有子组件),因此此解决方案不切实际.
I am trying to create a Swing panel whose elements have a different font size than the rest of the swing application. Initially, using setFont
for a couple of components didn't pose any problems. Now I have several components (and all their subcomponents), so this solution is impractical.
我搜索了有关更改挥杆组件的默认UI属性的信息.我发现的大部分是使用UIManager,它会全局更改属性.这对我不起作用,因为我想保留所有其他面板的当前字体设置.
I have searched about changing the default UI properties of swing components. What I have found is mostly using the UIManager, which changes the properties globally. This doesn't work for me because I want to keep the current font settings for all the other panels.
目前(由于我不喜欢先不尝试就发布内容),所以我有一个像这样的算法:
For the moment (and since I don't like to post without trying something out first), I have an algorithm like this:
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));
}
}
}
问题在于:
- 它不包括某些摆动元素,例如其边框.
- 动态添加其他组件时必须调用此函数
问题:还有另一种方法来更改Swing面板及其所有组件,元素等(即面板中的所有内容)的字体属性吗?
Question: Is there another way to change the font properties of a Swing panel and all its components, elements, etc (i.e. everything in the panel) ?
感谢您的想法
推荐答案
您可以使用此技巧:
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);
}
}
产生:
这篇关于更改JPanel及其所有元素的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!