我有一些移动文件的代码,并希望在复制文件时实现进度指示器,但我在更新进度条时遇到问题 - 它只是停留在 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。
Do I need to use SwingWorker to get this working properly?
SwingWorker 实际上是从 EDT 外部运行 copyFiles() 代码的一种方式。
关于java - JProgressBar 更新不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8812718/