我有StringBuffer
设置为 JTextArea
。现在我想要 StringBuffer
中的字符串的一部分根据某些条件加下划线怎么办?
假设我需要显示“以 4.00 的价格购买 Apple”之类的内容,但带有下划线的“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) {}
您还可以创建操作来更改任何选定文本的属性。阅读 Swing 教程中关于 Text Component Features 的部分了解更多信息和工作示例。
关于java - 将带下划线的文本设置为文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31202557/