我在Netbeans(Java)中使用了一个文本区域,我想强调文本中的某些关键字,比如编程中的语法高亮。我怎么能在Netbeans的JTextArea中做到这一点?
答案 0 :(得分:3)
您无法使用JTextArea突出显示各个文本。
我建议使用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);
// Change attributes on some text
doc.setCharacterAttributes(0, 5, keyWord, false);