Blinking text feature in the JEditorPane Component 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). 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 |
||||||||