在Java中,可以使用Swing库中的JProgressBar组件和SwingWorker类来实现多线程进度条
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MultiThreadedProgressBar extends JFrame {
public MultiThreadedProgressBar() {
setTitle("多线程进度条");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
}
public class MultiThreadedProgressBar extends JFrame {
private JProgressBar progressBar;
public MultiThreadedProgressBar() {
setTitle("多线程进度条");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
progressBar = new JProgressBar();
progressBar.setValue(0);
progressBar.setStringPainted(true);
add(progressBar, BorderLayout.CENTER);
}
}
class MySwingWorker extends SwingWorker<Void, Void> {
private JProgressBar progressBar;
public MySwingWorker(JProgressBar progressBar) {
this.progressBar = progressBar;
}
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i <= 100; i++) {
Thread.sleep(50); // 模拟耗时操作
setProgress(i);
}
return null;
}
@Override
protected void process(List<Void> chunks) {
// 这里可以处理任务执行过程中的中间结果,但在这个例子中不需要
}
@Override
protected void done() {
JOptionPane.showMessageDialog(null, "任务完成!");
}
}
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MultiThreadedProgressBar frame = new MultiThreadedProgressBar();
frame.setVisible(true);
MySwingWorker worker = new MySwingWorker(frame.progressBar);
worker.execute();
});
}
}
现在运行Main类,你将看到一个多线程进度条在窗口中显示。SwingWorker子类在后台线程中执行任务,并在任务完成时更新进度条。