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.
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.
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.