1

Using AttributedString and addAttribute() I can write out a line of formatted text, with the formatting set to sub-ranges of the text.

Using LineBreakMeasurer.nextLayout().getAdvance() I can then both center & right align. (And left align is trivial.)

But how do I tell it to justify it to a left and right margin? I think it's to use TextAttribute.JUSTIFICATION but it's not clear how to use it. It says a range of 0..1 and 1 clearly is no impact, but it's not clear how other settings will cause a spacing out of the text.

Or... am I going about this all wrong? I need to write lines of text (not paragraphs - I handle the line breaks) where the lines of text can have different formatting over sub-ranges of the text. And the line can be left, center, right, or justify aligned.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • Just to add to your research the class FontMetrics (g2d.getFontMetrics()) can help you measure the texts for pixel sizes – Marcos Vasconcelos Apr 26 '18 at 16:29
  • Did you specify a width for you text ? From doc "The default value is 1, indicating that justification should use the full width provided" so maybe your problem is there. – Lutzi Apr 26 '18 at 16:31
  • Possible duplicate https://stackoverflow.com/questions/400566/full-justification-with-a-java-graphics-drawstring-replacement?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Lutzi Apr 26 '18 at 16:38
  • @Lutzi - that example shows how to calculate soft line breaks. But it doesn't (unless I'm missing something) render justified aligned text. – David Thielen Apr 26 '18 at 16:47

1 Answers1

1

The trick is to use TextLayout.getJustifiedLayout(). That does it - no need for TextAttribute.JUSTIFICATION.

David Thielen
  • 28,723
  • 34
  • 119
  • 193