我有一些代码可以移动文件,并希望在复制文件时实现进度指示器,但我在更新进度条时遇到了问题,它只是停留在0。以下是有问题的相关代码:
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);
}
}
}
我需要使用SwingWorker才能正常工作吗?谢谢你的帮助。
要回答您关于进度条为什么不更新的问题:
您的JProgressBar没有更新,因为您在copyFiles()方法中阻塞了事件调度线程(EDT)。
您永远不应该用长时间运行的操作来阻止EDT。
如果从EDT调用actionPerformed回调,那么您也从EDT中调用copyFiles(),会发生什么情况。
您应该从另一个线程运行copyFiles。
我需要使用SwingWorker才能正常工作吗?
SwingWorker确实是从EDT外部运行copyFiles()代码的一种方法。
我会使用ProgressMonitor
。下面是一个用法示例。
您的答案是:
progressBar.update(progressBar.getGraphics());