Resize the JPanel font and all its elements

I am trying to create a Swing panel whose elements have a different font size than other swing applications. Initially, using setFont for multiple components was not a problem. Now I have several components (and all their subcomponents), so this solution is impractical.

I was looking to change the default user interface properties for swing components. What I found mainly uses UIManager, which modifies properties around the world. This does not work for me because I want to keep the current font settings for all other panels.

At the moment (and since I don’t like to publish without trying to do something 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)); } } } 

The problem is that:

  • it does not include certain rotation elements, such as its boundary.
  • I have to call this function when I dynamically add other components

Question: Is there any other way to change the font properties of the Swing panel and all its components, elements, etc. (i.e. everything in the panel)?

Thanks for your ideas.

+6
java swing
source share
2 answers

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

It produces:

enter image description here

+4
source share

you can override the add method on the base component and apply the font to the added components and their children. this will save you from manually applying the font when components are added later.

+1
source share

All Articles