我试图突出显示 JEditorPane 中的一些代码,如下所示:
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){}
}
}
这将一次突出显示一个字符,并且所有字符都将保持突出显示。现在,我想要相同的行为(所有字符都保持突出显示),但我想更改突出显示之间的文本,如下所示:
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){}
}
}
请注意窗格中的文本正在更改,然后我正在应用新的突出显示。旧的亮点消失了——我希望它们留下来。我的假设是每次 setText() 时高光都会消失。那么,有没有办法在更改文本的同时保持文本组件中的高亮显示呢?