在下面的代码中,我试图显示以 25/秒的频率变化的计数器。但是,即使将延迟 40ms 更改为 80ms,它也会闪烁并且不会顺利刷新,它仍然会闪烁。如何使刷新更顺畅?-我使用 JTextPane 的原因是因为我想以 HTML 格式显示(并刷新)文本
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.text.html.HTMLDocument;
public class ColumnsInJTextPane
{
public ColumnsInJTextPane(JTextPane textPane, String sLeft, String sRight)
{
StringBuilder text = new StringBuilder( 150 );
text.append( "<html><body>" );
text.append( "<table border='0' style='margin:4px 2px 12px 6px' width='400'>" );
text.append( "<tr>" + "<td width='200' align='left' valign='top' style='margin-right:8px'>" );
text.append( sLeft );
text.append( "</td>" );
text.append( "<td align='left' valign='top' style='margin-right:8px'>" );
text.append( sRight );
text.append( "</td>" + "</tr>" );
text.append( "</table>" );
text.append( "</body></html>" );
textPane.setText( text.toString() );
}
public static void main( String[] args )
{
JTextPane textPane = new JTextPane();
textPane.setContentType( "text/html" );
textPane.setEditable(false);
//to get a consistent (body) appearance use the font from the Label using a CSS rule (instead of the value in javax.swing.text.html.default.css)
Font font = UIManager.getFont( "Label.font" );
String bodyRule =
"body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize()*2 + "pt; }";
((HTMLDocument) textPane.getDocument()).getStyleSheet().addRule( bodyRule );
JFrame frame = new JFrame();
frame.setSize(new Dimension (350,200));
frame.add( textPane );
frame.setVisible( true );
for (int i = 0; i < 100000; i++) {
try {
Thread.sleep(40); // even changing it to 80 would not help, it still flickers upon repaint
} catch (InterruptedException e) {
e.printStackTrace();
}
new ColumnsInJTextPane(textPane, Integer.toString(i*10000), Integer.toString(i*2000));
}
}
}