在下面的代码中,我试图显示一个频率为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));
}
}
}
答案 0 :(得分:2)
你正在主线程中做所有事情!!! :
Swing使用EDT(事件调度线程)进行GUI相关任务和处理动作事件。将您的GUI创建对象和代码放在SwingUtilities.invokeLater(new Runnable(){})
对于重复的GUI更新任务,请在Swing中使用javax.swing.Timer
。