Java ProgressMonitorInputStream using existing JPr

2020-03-30 02:17发布

问题:

I'm just playing about with Java's ProgressMonitorInputStream to monitor data as it flows through a BufferedInputStream. Here is the code I'm currently trying:

InputStream in = new BufferedInputStream(
     new ProgressMonitorInputStream(
     new JFrame(),"Scanning",new FileInputStream(dir.getSearchInputFile())));

This works perfectly fine, and pops up a new JFrame window with a progress bar that displays the progress of the input stream.

Is there anyway of getting the ProgressMonitorInputstream to update an existing JProgressBar that exists within another JFrame?

I've tried various methods, such as passing in a JProgressBar with the constructor, or trying to specify the frame within the parameters. Each time I try, I just get a new JFrame.

Am I going about this all wrong?

Any input would be greatly appreciated.

Thanks

回答1:

The SwingWorker whose progress is being monitored doesn't care who's listening. Simply implement the PropertyChangeListener interface in the other frame and add the listener to the worker, as shown in ProgressMonitorDemo.

Addendum: As a concrete example, add a progress bar to the demo:

private JProgressBar bar = new JProgressBar();

Add it in the panel's constructor:

this.add(bar);

Update it in the panel's propertyChange() listener:

bar.setValue(progress);