代码之家  ›  专栏  ›  技术社区  ›  YuppieNetworking

更改JPanel及其所有元素的字体大小

  •  6
  • YuppieNetworking  · 技术社区  · 15 年前

    我正在尝试创建一个Swing面板,其元素的字体大小与Swing应用程序的其余部分不同。最初,使用 setFont

    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));
            }
        }
    }
    

    问题是:

    问题:

    2 回复  |  直到 15 年前
        1
  •  4
  •   aioobe    10 年前

    你可以用这个技巧:

    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);
        }
    }
    

    生产:

    enter image description here

        2
  •  1
  •   pstanton    15 年前

    add