Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Color;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

public class Main {
    static MyHighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);

    public static void main(String[] args) throws Exception {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JEditorPane jep = new JEditorPane();
        jep.setText("Hello to the public");
        frame.add(jep);
        frame.pack();
        frame.setVisible(true);

        highlight(jep, "public");
    }

    public static void highlight(JTextComponent textComp, String pattern) throws Exception {
        removeHighlights(textComp);

        Highlighter hilite = textComp.getHighlighter();
        Document doc = textComp.getDocument();
        String text = doc.getText(0, doc.getLength());
        int pos = 0;

        while ((pos = text.indexOf(pattern, pos)) >= 0) {
            hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
            pos += pattern.length();
        }

    }

    public static void removeHighlights(JTextComponent textComp) {
        Highlighter hilite = textComp.getHighlighter();
        Highlighter.Highlight[] hilites = hilite.getHighlights();

        for (int i = 0; i < hilites.length; i++) {
            if (hilites[i].getPainter() instanceof MyHighlightPainter) {
                hilite.removeHighlight(hilites[i]);
            }
        }
    }
}

class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {

    public MyHighlightPainter(Color color) {
        super(color);
    }
}