Skip to main content

AttributedString problem

3 replies [Last post]
Joined: 2006-02-14


AttributedString/AttributedCharacterIterator/LineBreakMeasurer/TextLayout ignores the font setting. In the following code:

FontRenderContext frc = new FontRenderContext(null, false, true);
String text = "hi there";
int len = text.length();
AttributedString as = new AttributedString(text);
as.addAttribute(TextAttribute.FONT, new java.awt.Font("Tahoma", java.awt.Font.PLAIN, (int) (12.0 + 0.5)), 0, len);
as.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, 0, len);
AttributedCharacterIterator aci = as.getIterator();
LineBreakMeasurer lbm = new LineBreakMeasurer(aci, BreakIterator.getLineInstance(new Locale("en", "US")), frc);
TextLayout tl = lbm.nextLayout((float) 9072 / 20.0f);
System.out.println("width = " + tl.getAdvance());
System.out.println("chars = " + tl.getCharacterCount());

Calling the following:
as.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, 0, len);

makes no difference in the results. It always returns a measurement for normal (not bold) text. What is going on?

thanks - dave

ps - I know I can pass Font.BOLD to the Font() ctor. However, the addAttribute() allows various weights for bold which we use. SO it's not always WEIGHT_BOLD and so we need to use the addAttribute() approach.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-01-05

TextAttribute.FONT takes precedence over TextAttribute.WEIGHT, so it will use the weight in the FONT property and ignore the WEIGHT property.

This is easily fixed. Dont use TextAttribute.FONT at all. Instead consider:

AttributedString as = new AttributedString(text);
as.addAttribute(TextAttribute.FAMILY, "Tahoma");
as.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
as.addAttribute(TextAttribute.SIZE, new Float(12.5f));

This should produce the desired results. Also for truly accurate results, it is best not to construct a FontRenderContext directly, but to obtain one from a Graphics2D object. eg:

Graphics2D g2d = (Graphics2D)getGraphics();
// add any rendering hints that will be used in rendering, such as anti-aliasing hints
FontRenderContext frc = g2d.getFontRenderContext();
Joined: 2006-02-14


My understanding is that TextAttribute.FAMILY is set to values such as "Serif", "SansSerif", "Fixed" and not to the font name.

If so, I can't use it as "Arial Black" is very different from "Arial Narrow". Or is the javadocs for this wrong?

thanks - dave

ps - I have to create the FontRenderContext directly because my app has no UI and therefore no way to get a Graphics2D object.
Joined: 2006-02-14

Hi all;

I got this from a contact at Sun. TextAttribute.FAMILY [b]can[/b] be the family or the font name. The points in this forum are covered in the 1.6 docs at:

I believe this holds from at least java 1.3 on based on my testing.

thanks - dave