Set the same font for all Java components

I want to set a specific font for the entire component in JPanel , but I prefer this question to be even more general and not limited to JPanel. How to set a font to the list of components in a container (JFrame or JPanel)?

+7
source share
4 answers

Here is a simple way that allows you to specify a font for the entire tree of components in any container (or just a simple component, it does not matter):

 public static void changeFont ( Component component, Font font ) { component.setFont ( font ); if ( component instanceof Container ) { for ( Component child : ( ( Container ) component ).getComponents () ) { changeFont ( child, font ); } } } 

Just pass your panel and special font to this method, and you will also receive all refactoring for children.

+16
source

- You can use UIManager for this ....

For example:

 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); } } 
+8
source

Set the font values ​​in the UIManager for the components you want to change. For example, you can set the font used for labels by doing:

 Font labelFont = ... ; UIManager.put("Label.font", labelFont); 

Please note that different appearance (L & F) may have different properties for the UIManager class, so if you move from one L & F to another, you may have problems.

+3
source

Inspired by Mikle Grains Answer I used its code to increase the font of each component as a percentage, getting the old fontsize

  public static void changeFont(Component component, int fontSize) { Font f = component.getFont(); component.setFont(new Font(f.getName(),f.getStyle(),f.getSize() + fontSize)); if (component instanceof Container) { for (Component child : ((Container) component).getComponents()) { changeFont(child, fontSize); } } } 
+2
source

All Articles