在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子類在后臺線程中執行任務,并在任務完成時更新進度條。