将带下划线的文本设置为textarea

Setting underlined text to textarea

我有 StringBuffer 设置为 JTextArea。现在我想根据某些条件给 StringBuffer 中的部分字符串加下划线怎么办?

假设我需要显示像 Buy Apple at price 4.00 但文本 Apple 有下划线。

使用JTextPane。默认支持自动换行,可以设置任意一段文字的属性。

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) {}

您还可以创建操作来更改任何选定文本的属性。阅读有关 Text Component Features 的 Swing 教程部分,了解更多信息和工作示例。