tags:

views:

147

answers:

2

Hello all,

I am trying to create a Swing panel whose elements have a different font size than the rest of the swing application. Initially, using setFont for a couple of components didn't pose any problems. Now I have several components (and all their subcomponents), so this solution is impractical.

I have searched about changing the default UI properties of swing components. What I have found is mostly using the UIManager, which changes the properties globally. This doesn't work for me because I want to keep the current font settings for all the other panels.

For the moment (and since I don't like to post without trying something out first), I have an algorithm like this:

public static void fixFont(Container c) {
    c.setFont(c.getFont().deriveFont(10.0f));
    Component[] comp = c.getComponents();
    for (int i=0;i<comp.length;++i) {
        if (comp[i] instanceof Container) {
            fixFont((Container) comp[i]);
        } else {
            comp[i].setFont(comp[i].getFont().deriveFont(10.0f));
        }
    }
}

The problem is that:

  • it doesn't include certain swing elements like its border.
  • I have to call this function when I add other components dynamically

Question: Is there another way to change the font properties of a Swing panel and all its components, elements, etc (i.e. everything in the panel) ?

Thanks for your ideas

+1  A: 
aioobe
I want to change only the fonts of the panel and all its elements. I don not want to change the font of other panels. Doing this using the UIManager changes the font for all Swing components.
YuppieNetworking
Ah, good point. Didn't realize what you needed really. Not sure how (or if it's possible) to solve it now that I understand your question.
aioobe
One "backup" solution would be to do just as you do it now, but to also check and update borders through `getBorder` and `instanceof TitledBorder` / `TitledBorder.setTitleFont` etc
aioobe
A: 

you could override the add method on your base component and apply the font to the added components and their children there. this would save you applying the font manually when components are added later.

pstanton
Still wont work for borders etc...
aioobe
It will not work for all elements inside the panel. For example: a JPanel that has a JPanel with a label.
YuppieNetworking
might not work for borders, but you could put any code you like in your 'add' implementation, so there's no reason why you couldn't call something like the code in your question. basically, i don't think there's an easy answer for this. it's an 'untidy' operation.
pstanton