在JTextArea(Netbeans)中突出显示关键字

时间:2015-10-21 03:39:56

标签: java swing netbeans syntax-highlighting jtextarea

我在Netbeans(Java)中使用了一个文本区域,我想强调文本中的某些关键字,比如编程中的语法高亮。我怎么能在Netbeans的JTextArea中做到这一点?

1 个答案:

答案 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);