Articles Projects Tips Downloads Contacts About

Blinking text feature in the JEditorPane Component
By Stanislav Lapitsky

Sometimes we would like to emphasize a fragment of text.  Be sure user will pay attention to blinking word. I tied to provide a simple example how to achieve this in JEditorPane (actually in any JTextComponent extension).
All we need in fact is to add a highlight with custom painter. The painter has a color field passed by user in the constructor and blink rate parameter (in milliseconds).

The painter starts Timer which swap background and selection colors and calls repaint.

The source code shows how to achieve this.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.DefaultHighlighter.*;

public class Blink extends JEditorPane {
    public Blink() {
        setText("Blinking word text is a simple example of the feature in JEditorPane.");
        try {
            addBlink(14, 18,Color.red, 300);
        }
        catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }

    public void addBlink(int startPos, int endPos, Color blinkColor, int blinkRate) throws BadLocationException {
        getHighlighter().addHighlight(startPos, endPos, new BlinkPainter(blinkColor, blinkRate));
    }

    public static void main(String[] args) {
        JFrame fr=new JFrame("Blinking text in JEditorPane");
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.setSize(400,300);
        fr.getContentPane().add(new Blink());
        fr.setLocationRelativeTo(null);
        fr.setVisible(true);
    }

    class BlinkPainter extends DefaultHighlightPainter {
        Color blinkColor;
        Color activeColor;
        public BlinkPainter(Color c, int blinkRate) {
            super(null);
            blinkColor=c;

            Timer t=new Timer(blinkRate, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    changeColor();
                }
            });
            t.start();
        }

        protected void changeColor() {
            if (activeColor==blinkColor) {
                activeColor=getBackground();
            }
            else {
                activeColor=blinkColor;
            }
            repaint();
        }

        public Color getColor() {
            return activeColor;
        }

    }
} 

Back to Table of Content