Syntax-Highlighting in JTextPane using SwingWorker
Asked Answered
H

1

9

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);
    }
}

and Modify class is:

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

And my output is:

enter image description here

i wanna to display all keywords with specified text style.
How will i get desired output.

Hypochlorite answered 30/9, 2013 at 15:39 Comment(1)
doInBackground is workers thread, not designated to change anything in Swing GUI, you would need to use publish() or setProcessCaine
O
5

Seems like your highlighting offset are off.

See Text and New Lines for the probable cause and a simple solution.

Olein answered 30/9, 2013 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.