private AttributedString prepareAttributedString() { List<StyledText> textChunks = getTextChunks(); StringBuilder buf = new StringBuilder(); for (StyledText textChunk : textChunks) { buf.append(textChunk.getText()); } AttributedString attributedString = new AttributedString(buf.toString()); int startIndex = 0; int endIndex = 0; for (StyledText textChunk : textChunks) { if (textChunk == textChunks.get(textChunks.size() - 1)) endIndex = buf.length(); else endIndex = startIndex + textChunk.getText().length(); attributedString.addAttribute(TextAttribute.FONT, textChunk.getFont(), startIndex, endIndex); attributedString.addAttribute( TextAttribute.FOREGROUND, textChunk.getColor(), startIndex, endIndex); startIndex += textChunk.getText().length(); } return attributedString; }
@Test public void multipleStylesAppliedToLine() throws Exception { createStyles(); parent.setSize(200, 100); panel.setText("<my_style>some </my_style><my_other_style>text</my_other_style>", parent); panel.buildLines(); List<StyledText> chunks = panel.getTextChunks(); StyledText layout = chunks.get(0); assertEquals(5, layout.getText().length()); assertSubString("family=Helvetica", layout.toString()); assertSubString("name=Helvetica", layout.toString()); assertSubString("style=bold", layout.toString()); assertSubString("size=20", layout.toString()); StyledText layout2 = chunks.get(1); assertEquals(5, layout.getText().length()); assertSubString("family=Dialog", layout2.toString()); assertSubString("name=Cuneiform", layout2.toString()); assertSubString("style=italic", layout2.toString()); assertSubString("size=19", layout2.toString()); }