在Java中,可以使用Swing库中的JProgressBar组件和SwingWorker类来实现多线程进度条
- 首先,导入所需的库:
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
- 创建一个JFrame窗口,并设置其基本属性:
public class MultiThreadedProgressBar extends JFrame { public MultiThreadedProgressBar() { setTitle("多线程进度条"); setSize(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } }
- 创建一个JProgressBar组件,并将其添加到窗口中:
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); } }
- 创建一个SwingWorker子类,用于在后台线程中执行任务并更新进度条:
class MySwingWorker extends SwingWorker{ 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 chunks) { // 这里可以处理任务执行过程中的中间结果,但在这个例子中不需要 } @Override protected void done() { JOptionPane.showMessageDialog(null, "任务完成!"); } }
- 在主方法中创建并显示窗口,同时启动SwingWorker线程:
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子类在后台线程中执行任务,并在任务完成时更新进度条。