I've never used Java AWT before and now I've got a piece of code that displays a JFrame
and sets the font property for all child components to the same value. I'd like to set the property in one place only. How can I do this?
In .NET/WinForms, child controls inherit from their parent controls, thus it would be enough to set the font for the Form
instance to have it propagate to all controls. Unexpectedly, this doesn't seem to hold for AWT.
The following little code sets the font for all components recursively:
private void setFontForAll(JFrame f, java.awt.Font font) {
f.setFont(font);
setFontRecursive(f.getContentPane().getComponents(), font);
}
private static void setFontRecursive(Component[] components, java.awt.Font font) {
for (Component c : components) {
c.setFont(font);
if (c instanceof java.awt.Container)
setFontRecursive(((java.awt.Container)c).getComponents(), font);
}
}
However, it has four drawbacks:
TitledBorder
s of JPanel
s don't get set.The UIManager class is the thing you need. Before you build your user interface simply tell it what fonts you want. Be warned though; there are a lot of font keys defined and if you want to change them all, you'll have to set them all.
UIManager.put( "Button.font", new Font( "Verdana", Font.BOLD, 12f );
UIManager.put( "Label.font", new Font( "Wingdings", Font.ITALIC, 12f );
// ...etc...
You can see the keys and values that are set by programmatically inspecting UIManager.getDefaults() which returns a hashtable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With