英文:
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 ";
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论