Java Swing - 如何做一個(gè)Thread中的耗時(shí)任務(wù)和更新JProgressBar與SwingUtilities
我們想知道如何做一個(gè)Thread中的耗時(shí)任務(wù)和更新JProgressBar與SwingUtilities。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
int minValue = 0;
int maxValue = 100;
int counter = 0;
JProgressBar progressBar = new JProgressBar();
public Main() {
super();
setSize(300, 100);
progressBar.setMinimum(minValue);
progressBar.setMaximum(maxValue);
progressBar.setStringPainted(true);
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread runner = new Thread() {
public void run() {
counter = minValue;
while (counter <= maxValue) {
Runnable runme = new Runnable() {
public void run() {
progressBar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
});
getContentPane().add(progressBar, BorderLayout.CENTER);
getContentPane().add(start, BorderLayout.WEST);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}