Skip to content
Advertisement

Changing font-size at runtime in a Swing application

A lot of web sites these days have an option to let the user increase or decrease the size of the font that appears on the site. I’d like to add similar functionality to my Java Swing app, with an option to change the font to either a larger size or revert to standard size. The user would be able to do this at runtime, via a menu item.

The current version of my code isn’t working very well – the code iterates over the keys stored in UIManager/UIDefaults, and for each key that’s a Font, my code derives a new font with the target point size (e.g., if it’s larger, then the new point size is usually 16; otherwise, if going to regular size, it’s usually 11), and then puts that key and new font in UIManager. Afterwards, the code calls SwingUtilities.updateComponentTreeUI() on the frame, and then packs the frame.

The code will increase the font once, but switching back to regular size has no effect. This is especially noticeable with the menu bar.

Am I going about this the right way? Should I instead create a new look and feel with the larger point size, or use some other method entirely?

Thanks in advance for any help.

Advertisement

Answer

The code will increase the font once, but switching back to regular size has no effect

I believe you need to update the UIManager with a FontUIResource, not just a Font.

Edit:

You should be able to use:

SwingUtilities.updateComponentTreeUI(frame);

Check out the section from the Swing tutorial on Changing the LAF After Startup;

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement