简体   繁体   English

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

[英]Highlighting keywords in JTextArea (Netbeans)

I'm using a text area in Netbeans(Java), and I want to highlight certain keywords in the text, something like syntax-highlighting in programming. 我正在使用Netbeans(Java)中的文本区域,并且想突出显示文本中的某些关键字,例如编程中的语法突出显示。 How could I do that but within a JTextArea in Netbeans? 在Netbeans的JTextArea中,我该怎么做?

You can't use a JTextArea to highlight individual pieces of text. 您不能使用JTextArea突出显示单个文本。

I would suggest a JTextPane so you can use styled attributes. 我建议使用JTextPane以便您可以使用样式化的属性。

The basic code would be something like: 基本代码如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM