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:
- Extra code, which might actually be quite inefficient for large forms with nested layout panels.
- Code is non-generic. If I need to do the same for another property in future, I've got to rewrite the method (or refactor it to be more general at the expense of conciseness).
- Usage is non-declarative, i.e. has to be called at the very end of the form creation (after all child components have been initialized and added) instead of anywhere in a declarative manner.
- It doesn't work. Components are set correctly but not all things are components. For example, the
TitledBorder
s ofJPanel
s don't get set.