RocketRuwan
RocketRuwan

Reputation: 233

How to change Font in multiple Components at once which are already assigned with a Font?

How do I change an apply a different Font into multiple Components or the entire JFrame or the entire Swing Application, which some Components are already assigned with a Font, after the UI is generated?

The task I'm trying to do is to change and apply a different or custom Font into JFrame upon loading which is in a NetBeans Project therefore some of the Components are already assigned with a Font by its auto generated methods.

So far I have tried setting the Font using the UIManager into its default keys, and then calling SwingUtilities.updateComponentTreeUI(jframe); but it only applied the Font to the Components those have not been assigned with a Font already. Here is how I made the attempt (with the example of this answer.).

        Enumeration enc = UIManager.getDefaults().keys();

        while (en.hasMoreElements() ) {
            Object key = en.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof Font) {
                UIManager.put(key, font);
            }
        }

And then calling,

SwingUtilities.updateComponentTreeUI(jframe);

As it was not entirely successful, then I tried to set the Font in all the Components in the JFrame and then calling validate(); followed by repaint();, but it didn't make any effect whatsoever. This is how I tried to do it.

        Component[] comps = this.getComponents();
        for (Component comp : comps){
            comp.setFont(font);
        }

And then calling,

this.validate();
this.repaint();

Have I done those previous steps correctly or is there any error I have made? If not, what is the correct way to accomplish my task? And also, even though I need to change the Font in all the Components, their existing Font sizes and Font styles are needed to be preserved as well.

Thank you!

Upvotes: 1

Views: 430

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

Change the Pluggable Look and Feel to a (possibly custom) PLAF is the best, most robust way to do it. See this answer for tips on how to change the PLAF after the GUI is visible.

See the Modifying the Look and Feel lesson of the Java Tutorial for further details. See below for examples of one user interface using two different PLAFs.

Upvotes: 4

Related Questions