Reputation: 437
I have some code that moves files around and would like to implement a progress indicator while the files are being copied, but I'm having problems getting the progress bar to update - it just stays at 0. Here is the relevant code in question:
public class SomeClass extends JFrame implements ActionListener
{
private static SomeClass myprogram = new SomeClass();
private JProgressBar progressBar = new JProgressBar();
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
myprogram.initGUI();
}
});
}
private void initGUI()
{
JButton button1 = new JButton("Another Button");
JButton button2 = new JButton("Copy");
// other GUI Code
}
@Override
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton) e.getSource();
String text = button.getText();
if (text.equalsIgnoreCase("Copy"))
{
copyFiles();
}
else
{
doSomethingElse();
}
}
public void copyFiles()
{
for (int i = 0; i < someNumber; i++)
{
//Code to copy files
progressBar.setValue((i * 100) / someNumber);
}
}
}
Do I need to use SwingWorker to get this working properly? Thanks for any help.
Upvotes: 1
Views: 1416
Reputation: 11
YOUR answer is:
progressBar.update(progressBar.getGraphics());
Upvotes: 0
Reputation: 6335
To answer your question as to why your progress bar ain't updating:
Your JProgressBar ain't updating because you're blocking the Event Dispatch Thread (EDT) in your copyFiles() method.
You should never ever block the EDT with long-running operation.
What happens it that the actionPerformed callback is called from the EDT, so you're calling copyFiles() from the EDT too.
You should run the copyFiles from another thread.
Do I need to use SwingWorker to get this working properly?
SwingWorker would, indeed, be one way to run the copyFiles() code from outside the EDT.
Upvotes: 4