我有一些代码可以移动文件,并希望在复制文件时实现进度指示器,但是我在进度条更新时遇到问题 - 它只是保持为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才能使其正常工作?谢谢你的帮助。
答案 0 :(得分:4)
回答有关进度条未更新的原因的问题:
您的 JProgressBar 未更新,因为您在 copyFiles()方法中阻止了事件调度线程(EDT)。< / p>
你永远不应该在长时间运行的情况下阻止EDT。
从EDT调用 actionPerformed 回调会发生什么,所以你也从EDT调用 copyFiles()。
您应该从另一个线程运行 copyFiles 。
实际上,SwingWorker是从EDT外部运行 copyFiles()代码的一种方法。我是否需要使用SwingWorker才能使其正常工作?
答案 1 :(得分:3)
我会使用ProgressMonitor
。 Here's一个用法示例。
答案 2 :(得分:0)
您的回答是:
progressBar.update(progressBar.getGraphics());