2015-10-21 67 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);