使用SwingWorker的JTextPane中的语法突出显示 [英] Syntax-Highlighting in JTextPane using SwingWorker
本文介绍了使用SwingWorker的JTextPane中的语法突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 JTextPane 中突出显示文本.我正在使用 SwingWorker 在后台突出显示.但是我无法获得想要的输出.
我的代码如下:
主要类别:
I am trying to do text highlighting in JTextPane. I'm using SwingWorker to do highlighting in background. But i'm unable to get desired output.
My Code is as Follow:
Main Class:
class MultiColor {
private static void displayGUI() {
final JTextPane ta = new JTextPane();
JFrame frame = new JFrame("EXAMPLE");
JButton jb = new JButton("Change");
JScrollPane jsp = new JScrollPane(ta);
frame.add(jsp, BorderLayout.CENTER);
frame.add(jb, BorderLayout.PAGE_END);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
Modify mm = new Modify(ta);
mm.execute();
}
});
}
public static void main(String[] a) {
Runnable r = new Runnable() {
@Override
public void run() {
displayGUI();
}
};
SwingUtilities.invokeLater(r);
}
}
和修改类为:
class Modify extends SwingWorker<Void,Object> {
private JTextPane ta;
private StyleContext style;
private AttributeSet textStyle;
public Modify(JTextPane text) {
ta = text;
}
private void matching(String str){
style = StyleContext.getDefaultStyleContext();
textStyle = style.addAttribute(style.getEmptySet(),StyleConstants.Foreground, Color.red);
textStyle = style.addAttribute(textStyle,StyleConstants.FontSize, 15);
String regx = "\\b(class|int|void|static|final|public|private|protected|float|if|else|for|while|try|catch|boolean|import|return)\\b";
String input = str;
Pattern p = Pattern.compile(regx);
Matcher m = p.matcher(input);
while(m.find())
ta.getStyledDocument().setCharacterAttributes(m.start(),(m.end() - m.start()),textStyle, false);
}
@Override
protected Void doInBackground() {
matching(ta.getText());
return null;
}
@Override
protected void done() {
}
}
我的输出是:
我想显示具有指定文字样式的所有关键字.
我将如何获得所需的输出.
i wanna to display all keywords with specified text style.
How will i get desired output.
推荐答案
突出显示偏移量似乎已关闭.
Seems like your highlighting offset are off.
请参见文本和换行可能的原因和简单的解决方案.
See Text and New Lines for the probable cause and a simple solution.
这篇关于使用SwingWorker的JTextPane中的语法突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文