I am trying to highlight some code in a JEditorPane like this:
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class Driver
{
public static void main(String[] args)
{
try
{
//create a simple frame with an editor pane
JFrame frame = new JFrame("Highlight Test");
JEditorPane pane = new JEditorPane();
frame.getContentPane().add(pane);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//string to put in the pane
String text = "1234567890";
//grab the highlighter for the pane
Highlighter highlighter = pane.getHighlighter();
//store all the text at once
pane.setText(text);
//go through all the characters
for(int i = 0; i < text.length(); i++)
{
//highlight the latest character
highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
//sleep for a quarter second
Thread.sleep(250);
}
}catch(Exception ex){}
}
}
This will highlight the characters one at a time and all the characters will remain highlighted. Now, I'd like the same behavior (all the characters remain highlighted) but I'd like to change the text in between highlights, like this:
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class Driver
{
public static void main(String[] args)
{
try
{
//create a simple frame with an editor pane
JFrame frame = new JFrame("Highlight Test");
JEditorPane pane = new JEditorPane();
frame.getContentPane().add(pane);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//string to put in the pane
String text = "1234567890";
//grab the highlighter for the pane
Highlighter highlighter = pane.getHighlighter();
//go through all the characters
for(int i = 0; i < text.length(); i++)
{
//place a new string in the pane
pane.setText(pane.getText() + text.charAt(i));
//highlight the latest character
highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
//sleep for a quarter second
Thread.sleep(250);
}
}catch(Exception ex){}
}
}
Notice the text in the pane is changing and then I'm applying a new highlight. The old highlights go away- I'd like them to stay. My assumption is the highlights go away each time you setText(). So, is there any way to keep the highlights in the text component while changing the text?