【问题标题】:Syntax-Highlighting in JTextPane using SwingWorker使用 SwingWorker 在 JTextPane 中突出显示语法
【发布时间】:2013-09-30 15:39:26
【问题描述】:

我正在尝试在 JTextPane 中突出显示文本。我正在使用 SwingWorker 在背景中进行突出显示。但我无法获得所需的输出。
我的代码如下:
主类:

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() {
    }
}

我的输出是:

我想显示所有具有指定文本样式的关键字。
我将如何获得所需的输出。

【问题讨论】:

  • doInBackground 是工作线程,未指定更改 Swing GUI 中的任何内容,您需要使用 publish() 或 setProcess

标签: java swing jtextpane


【解决方案1】:

好像您的突出显示偏移已关闭。

请参阅Text and New Lines 了解可能的原因和简单的解决方案。

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 2011-08-06
    • 1970-01-01
    • 2012-05-15
    • 2011-07-21
    • 2012-04-04
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多