2015-10-21 70 views
0

我在Netbeans(Java)中使用了一个文本区域,并且我想突出显示文本中的某些关键字,例如编程中的语法高亮显示。我怎么能这样做,但在Netbeans的JTextArea内?在JTextArea中突出显示关键字(Netbeans)

+0

对于[示例](http://stackoverflow.com/questions/26986778/compare-two-strings-and-highlight-the-mismatch-wherever -found/26987044#26987044) – MadProgrammer

回答

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