views:

249

answers:

2

In my swing application, I have different types of text I'd like to display. For example, I want to display a heading text before a list of choices, something like:

    Select choice:
     a
     b

I want the "Select Choice" label to use the "Heading" font (something I define), and the choices to use the "Choice" font. This pattern will occur multiple places in my application, so ideally I'd like to centralize where the fonts are set.

My current approach is to use a factory to create the different label types:

LabelFactory.createHeadingLabel("LabelText");
LabelFactory.createChoiceLabel("ChoiceText");

The factory reads in a properties file specifying the fonts and I customize the labels when they are created in the factory. I know that using a factory like this works, but I'm not sure if there is a standard Swing convention for doing something like this. Any input would be appreciated.

+2  A: 

One other approach would be to extend JLabel.

You could still read the fonts in from a configuration file, but this way, you can create labels in a much more similar way to a regular JLabel.

private JLabel header = new HeaderJLabel("Header text");

All you would have to do is override the constructor for your custom labels.

Also, you should only read in the configuration file once. Load it into memory, and access it from memory from then on.

jjnguy
Yep, that was the other way I had considered. I don't generally do a lot of swing development, so I just didn't know if there was a standard "Swing" way to do things.
Jeff Storey
I don't believe there is a standard for what you are doing because it generally isn't too common.
jjnguy
It's not common to have multiple styles of text on a rich UI?
Jeff Storey
Most of the time, labels use similar styles. But I may be mistaken.
jjnguy
In my experience it's not that common. Bear in mind that Swing was designed in the late 90s. Graphic designers didn't have as much power in the NT 3.5 / Windows 2K days as they do in these days of Web 2.0. :)
David Moles
A: 

You can use limited html inside of many Swing components, so you may be able to use html to give your text different styles.

For instance, headingLabel.setText("< html><b>This text will be bold</b>< /html>"); Will give you a label with bold text.

Note: you have to remove the extra space from < html> and < /html>

instanceofTom