简体   繁体   English

从另一个类加入时重新绘制进度条

[英]Repaint progressbar when accesed from another class

I have a main class that has a JProgressBar . 我有一个有JProgressBar的主类。 From the main class I create a instance of a class (named Opener ) that has a method that reads text files that are usually big (>50000 lines of text). 从主类我创建一个类(名为Opener )的实例,该类具有读取通常较大的文本文件的方法(> 50000行文本)。

I pass a reference of the JProgressBar to the method of the Opener class that reads the txt files, so that progressbar is accessible from the Opener class. 我将JProgressBar的引用传递给Opener类的方法,该方法读取txt文件,以便可以从Opener类访问进度条。

The method is defined like this: 该方法定义如下:

 public void readtxtfile (JProgressBar myjProgressBar){....}

I call the method like this: 我这样称呼方法:

 Opener myopener = new Opener();
 myopener.readtxtfile (jProgressBar1);

I know that the reference to the progressbar is working correctly because I can set it visible from there (when the main class is created the progressbar is set not visible). 我知道对progressbar的引用工作正常,因为我可以从那里设置它(当创建主类时,进度条设置不可见)。

In the readtxtfile method I change the value of the progressbar as the txt file is read. readtxtfile方法中,我在读取txt文件时更改进度条的值。

 myjProgressBar.setValue(mycounter);
 myjProgressBar.revalidate();
 myjProgressBar.repaint();

My problem is that the progress bar is not repainted as its value changes. 我的问题是进度条没有重新绘制,因为它的值会发生变化。 What should I do? 我该怎么办?

PS: When the all reading of the txt file is done, the progress bar at last refreshes. PS:完成txt文件的全部读取后,进度条最后刷新。 But mean while nothing visible happens to it. 但意味着没有任何可见的事情发生。

It sounds more like you're trying to read the file from within the Event Dispatching Thread, preventing it from performing any repaints. 这听起来更像是你试图从事件调度线程中读取文件,阻止它执行任何重新绘制。

Probably the best choice would be to use a SwingWorker to run in the background and load the contents of the file and use it's property change support to update the progres. 可能最好的选择是使用SwingWorker在后台运行并加载文件的内容并使用它的属性更改支持来更新进度。

Take a look at Worker Threads and SwingWorker for details 有关详细信息,请查看Worker Threads和SwingWorker

Take a look at this and this for examples 看看这个这个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM