簡體   English   中英

如何在JTextPane無閃爍中重新繪制(刷新)文本

[英]How can I make repainting (refreshing) text in JTextPane flicker free

在下面的代碼中,我試圖顯示一個頻率為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));
      }
   }
}

你在主線程中做的一切!

  1. Swing使用EDT(事件調度線程)進行GUI相關任務和處理動作事件。 將您的GUI創建對象和代碼放在SwingUtilities.invokeLater(new Runnable(){})內的屏幕上顯示它們SwingUtilities.invokeLater(new Runnable(){})

  2. 對於重復的GUI更新任務,請在Swing中使用javax.swing.Timer

教程資源How to use Swing Timer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM