0

在下面的代码中,我试图显示以 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));
      }
   }
}
4

1 回答 1

2

你在主线程中做所有事情!!!

  1. Swing 使用 EDT(事件调度线程)来处理与 GUI 相关的任务和处理动作事件。把你的 GUI 创建对象和代码放到屏幕里面SwingUtilities.invokeLater(new Runnable(){})

  2. javax.swing.Timer在 Swing 中用于重复的 GUI 更新任务。

教程资源How to use Swing Timer

于 2013-10-25T22:09:08.233 回答