我试图突出显示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()时,亮点都会消失。那么,有没有办法在更改文本的同时保持文本组件中的高亮显示?
发布于 2011-06-17 04:45:50
我没有尝试下面的代码,但我建议的是尝试突出显示最新的字符和以前的字符,就像这样:
//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 previous characters
if (i > 0) {
for ( int j=i-1; j >= 0; j--)
highlighter.addHighlight(j, j+1 , DefaultHighlighter.DefaultPainter);
}
//highlight the latest character
highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
//sleep for a quarter second
// Thread.sleep(250);
}
}catch(Exception ex){}
https://stackoverflow.com/questions/6378270
复制相似问题