2013-10-25 71 views
0

在下面的代碼中,我試圖顯示計數器隨頻率變化25 /秒。但是,即使將延遲40ms更改爲80ms,它也會閃爍並且不會平滑刷新,但仍會閃爍。我怎樣才能讓清爽做平滑 - 我使用的JTextPane的原因是因爲我想顯示(和刷新)如何在JTextPane中無刷新刷新(刷新)文本

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

這傷害了我的眼睛! – Tdorno

回答

2

你是做在主線程一切都在HTML格式的文本!

  1. 搖擺使用EDT(事件調度線程)的GUI相關的任務和處理操作事件。把你的GUI創建對象和代碼在屏幕上顯示出來​​

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

教程資源How to use Swing Timer