Change font size of a JPanel and all its elements

后端 未结 2 1005
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 09:06

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 c

相关标签:
2条回答
  • You could use this trick:

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

    Produces:

    enter image description here

    0 讨论(0)
  • 2021-01-12 09:38

    you could override the add method on your base component and apply the font to the added components and their children there. this would save you applying the font manually when components are added later.

    0 讨论(0)
提交回复
热议问题