用纯JAVA原生方式实现代码高亮
实现代码高亮可以通过使用Java Swing库来实现。下面是一个简单的示例代码,可以将Java代码进行高亮显示:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class CodeHighlighter {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
frame.add(scrollPane);
// 设置字体和样式
Font font = new Font("Courier New", Font.PLAIN, 12);
textPane.setFont(font);
// 创建一个样式
StyleContext styleContext = StyleContext.getDefaultStyleContext();
Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
Style keywordStyle = styleContext.addStyle("KeywordStyle", defaultStyle);
StyleConstants.setForeground(keywordStyle, Color.BLUE);
// 定义关键字
String[] keywords = {"public", "class", "static", "void", "if", "else", "for", "while"};
// 获得文本内容
String code = "public class HelloWorld {\n" +
" public static void main(String[] args) {\n" +
" if (true) {\n" +
" System.out.println(\"Hello, World!\");\n" +
" } else {\n" +
" System.out.println(\"Goodbye, World!\");\n" +
" }\n" +
" }\n" +
"}";
// 设置代码高亮
StyledDocument doc = textPane.getStyledDocument();
try {
doc.insertString(0, code, null);
for (String keyword : keywords) {
int pos = 0;
while ((pos = code.indexOf(keyword, pos)) >= 0) {
doc.setCharacterAttributes(pos, keyword.length(), keywordStyle, false);
pos += keyword.length();
}
}
} catch (BadLocationException e) {
e.printStackTrace();
}
frame.setSize(400, 300);
frame.setVisible(true);
}
}
以上代码使用了JTextPane来显示文本,并使用StyledDocument来设置字体、样式和高亮。你可以根据需要自定义关键字和样式。运行代码后,将会以图形界面的形式展示高亮的Java代码
原文地址: http://www.cveoy.top/t/topic/iWXq 著作权归作者所有。请勿转载和采集!