0

I am having StringBuffer which is set to JTextArea. Now I want part of the string in StringBuffer to be underlined based on some condition how to do that?

Lets say I need to display like Buy Apple at price 4.00 but with text Apple underlined.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
MRavindran
  • 447
  • 2
  • 10
  • 24
  • 1
    A `JTextArea` supports plain text which means a single font (face, style and size). To do parts of text in different styles, we need to use a component like a `JLabel` or (closer to a `JTextArea`) a `JEditorPane`. – Andrew Thompson Jul 03 '15 at 09:03
  • But In my application i need the text to be word wrapped. JLabel doesnt support word wrapping. How about JEditorPane? – MRavindran Jul 03 '15 at 09:12
  • *"How about JEditorPane?"* Well.. how about it? What are you asking? BTW - Note that [`JLabel` (when showing HTML) **can** word wrap](http://stackoverflow.com/a/14011645/418556). – Andrew Thompson Jul 03 '15 at 09:53
  • I mean if we can do wrapping in JEditorPane. Yes I agree we can do wrapping using JLabel but my text will dynamically change based on the value from other components. in that case i can not use HTML tags – MRavindran Jul 03 '15 at 10:08

1 Answers1

2

Use JTextPane. It supports word wrapping by default and you can set the attributes of any piece of text.

JTextPane textPane = new JTextPane();
textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight" );
StyledDocument doc = textPane.getStyledDocument();

//  Define a keyword attribute

SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setUnderline(keyWord, Boolean.TRUE );
StyleConstants.setBold(keyWord, true);

//  Change attributes on some text

doc.setCharacterAttributes(20, 4, keyWord, false);

//  Add some text

try
{
    doc.insertString(0, "Start of text\n", keyWord );
}
catch(Exception e) {}

You can also create Actions to change the attributes of any selected text. Read the section from the Swing tutorial on Text Component Features for more information and working examples.

camickr
  • 321,443
  • 19
  • 166
  • 288