2013-06-24 66 views
0

我有一个下载程序显示我的百分比,但后来我添加了一个JLabel,它不刷新。所以它保持在0%。现在我的问题是,我如何每秒更新一次JLabel?刷新JLabel百分比Java

loaderText = "Loading is at "+TextDownloader.percentage+"%.."; 
JLabel loaderLabel = new JLabel(loaderText, JLabel.CENTER); 
loaderLabel.setForeground(Color.WHITE); 
aJPanel.add(loaderLabel); 
+2

不要堵塞EDT(事件指派线程) - 的图形用户界面将“冻结”当这种情况发生。而是为长时间运行的任务实施'SwingWorker'。有关更多详细信息,请参见[Swing中的并发](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 –

+1

还可以考虑使用['JProgressBar'](http://docs.oracle.com/javase/7/docs/api/javax/swing/JProgressBar.html)而不是'JLabel'或['ProgressMonitorInputStream'] (http://docs.oracle.com/javase/7/docs/api/javax/swing/ProgressMonitorInputStream.html)而不是。 –

+0

显示的代码似乎也不断添加标签,但我认为这只是针对该问题的代码提取。 –

回答

0

使用java.swing.Timer类刷新图形组件每秒:

final JLabel loaderLabel = new JLabel(JLabel.CENTER); 
loaderLabel.setForeground(Color.WHITE); 
aJPanel.add(loaderLabel); 

java.swing.Timer timer = new Timer(1000, new ActionListener(){ 
    String loaderText = "Loading is at "+TextDownloader.percentage+"%.."; 
    loaderLabel.setText(loaderText); 
};); 
timer.start(); 
+0

'TextDownloader'很可能阻止了EDT,所以这些代码在结束之前都不会进行可视化更改。 –

+0

“最有可能”?你能给我一个链接到源?我从来没有见过这样的代码。 – SeniorJD

+0

*“链接到源”*从上面的评论重复Bert。 *有关更多详细信息,请参阅[并发中的Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。* –