执行下看看结果
成功了
第二次点击“Start ProgressBar”按钮,进度条又可以正常工作了
O了
把最后的代码粘一份:
package chapter4;
import org.jvnet.substance.skin.CremeCoffeeSkin;
import org.jvnet.substance.skin.SubstanceAutumnLookAndFeel;
import org.jvnet.substance.skin.SubstanceSaharaLookAndFeel;
import javax.swing.*;
import javax.swing.plaf.metal.MetalProgressBarUI;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
/**
* Created by MyWorld on 2016/3/24.
*/
public class SwingJProgressBarDemo {
private static Thread thread = null;
public static void main(String[] args) throws UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(new SubstanceAutumnLookAndFeel());
SubstanceSaharaLookAndFeel.setSkin(new CremeCoffeeSkin());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingJProgressBarDemo().initGUI();
}
});
} private void initGUI() {
final JFrame frame = new JFrame("JProgressBarDemo");
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
final JProgressBar progressBar = new JProgressBar();
progressBar.setOrientation(JProgressBar.HORIZONTAL);
progressBar.setSize(200, 100);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setBorderPainted(true);
progressBar.setUI(new MetalProgressBarUI());
progressBar.setBackground(Color.BLUE);
progressBar.setForeground(Color.GREEN);
progressBar.setStringPainted(true);
frame.add(progressBar);
JButton btnStart = new JButton("Start ProgressBar");
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i <= 10; i++) {
final int finalI = i;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setValue(finalI * 10);
}
});
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
};
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
thread = new Thread(runnable);
thread.start();
}
}; btnStart.addActionListener(listener);
frame.add(btnStart); JButton btnCancel = new JButton("Cancel the task");
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (thread == null || !thread.isAlive()) {
return;
}
thread.interrupt();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setValue(0);
}
});
}
});
frame.add(btnCancel);
frame.setVisible(true);
}
}