package zikao.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class JProgressBarTest2 {
/*
JProgressBar使用的步骤:
1,创建JProgressBar的对象
public JProgressBar(int orient,int min,int max):
orient: 方向 min: 最小值 max: 最大值
2,设置属性
setBorderPainted(boolean b): 设置进度条是否有边框
setIndeterminate(boolean newValue): 设置该进度条是不是进度不确定的精度条
setStringPainted(boolean b): 设置进度条是否显示当前完成百分比
3,获取和设置当前进度条的进度状况
setValue(int n): 设置当前进度值
double getPercentComplete(): 获取进度条的完成百分比
String getString(): 返回进度字符串的当前值
*/
JFrame jFrame = new JFrame("JProgressBar测试");
JProgressBar bar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
JCheckBox indeterminate = new JCheckBox("不确定进度");
JCheckBox noBorder = new JCheckBox("不绘制边框");
public void init() {
//处理复选框的点击行为
indeterminate.addActionListener(e -> {
//获取indeterminate有没有被选中
boolean selected = indeterminate.isSelected();
//设置当前进度条不确定进度
bar.setIndeterminate(selected);
bar.setStringPainted(!selected);
});
noBorder.addActionListener(e -> {
boolean selected = noBorder.isSelected();
bar.setBorderPainted(!selected);
});
Box vBox = Box.createVerticalBox();
vBox.add(indeterminate);
vBox.add(noBorder);
//设置进度条的默认属性
bar.setStringPainted(true);
bar.setBorderPainted(true);
//把当前窗口的布局方式改为FlowLayout
jFrame.setLayout(new FlowLayout());
jFrame.add(vBox);
jFrame.add(bar);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.pack();
jFrame.setVisible(true);
SimulatorActivity simulaterActivity = new SimulatorActivity(bar.getMaximum());
new Thread(simulaterActivity).start();
Timer timer = new Timer(100, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int current = simulaterActivity.getCurrent();
bar.setValue(current);
}
});
timer.start();
//监听进度条的变化
bar.addChangeListener(e -> {
int value = bar.getValue();
if (value == simulaterActivity.getAmount()) {
timer.stop();
}
});
}
private static class SimulatorActivity implements Runnable {
//记录任务总量
private final int amount;
//记录当前完成量
private volatile int current;
public SimulatorActivity(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
public int getCurrent() {
return current;
}
@Override
public void run() {
while (current < amount) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
current++;
}
}
}
public static void main(String[] args) {
new JProgressBarTest2().init();
}
}
效果与上次主线程休眠一致