如何在JTextPane上实现语法着色。

huangapple go评论88阅读模式
英文:

how can i implement syntax coloring on a jtextpane

问题

我正在用Java制作一个代码编辑器,在实现语法高亮时遇到了问题。在互联网上找不到任何关于如何实现语法高亮的信息。我只找到了一个6年前的帖子,但那个方法不起作用。有人可以帮忙吗?

英文:

I'm making a code editor in java, and I ran into a problem while implementing syntax coluring. I could not find anything on the Internet on how to do it. I only found a 6 year old post that did not work.
Can anyone help?

答案1

得分: 1

第一步:您需要使用 jEditorPane。

第二步:创建一个高亮器,类似于下面这样(您可以更改高亮的颜色):

DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 0, 0, 75));

第三步:使用以下代码进行高亮显示:

try {
    jEditorPane1.getHighlighter().addHighlight("在此处放置起始字符的编号", "在此处放置结束字符的编号",
                                highlightPainter);
} catch (BadLocationException ex) {
}

示例:

JEditorPane text = new JEditorPane();
text.setText("Hi This is example good");
DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 0, 0, 75));
try {
    jEditorPane1.getHighlighter().addHighlight(3, 7, highlightPainter);
} catch (BadLocationException ex) {
}

这将使文本中的 "i This" 部分以下划线形式显示。

英文:

first: you need to use a jEditorPane

Second: Create a highlighter like this(you can change the color of the highligthe):

DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 0, 0, 75));

Third: to highlight use this

 try {
    jEditorPane1.getHighlighter().addHighlight("here put the number of the starting character", "Here put the ending number of character",
                                highlightPainter);
 } catch (BadLocationException ex) {
 }

Example.

  JEditorPane text = new JEditorPane();
  text.setText(" Hi This is example good");
  DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 0, 0, 75));
  try {
    jEditorPane1.getHighlighter().addHighlight(3, 7, highlightPainter);
 } catch (BadLocationException ex) {
 }

It should apper this underlined: "i This ";

huangapple
  • 本文由 发表于 2020年9月24日 22:41:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64048848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定