Swing 进度条
- 利用 JProgressBar 类可以创建进度条。进度条本质是就是一个矩形组件,通过填充它的一部分或者全部来指示一个任务的具体执行情况;
- 默认情况下,要确保既定任务的执行进度和进度条的填充区域成正比关系,如果并不确定任务的执行进度,则可以通过调用方法 setIndeterminate( boolean b) 来设置进度条的样式。设置为 true,表示不确定任务的执行进度,填充区域会来回滚动;设置为 false 则表示确定任务的执行进度;
- 一般来说,在进度条中不显示提示信息,可以调用 setStringPainted(boolean b) 来设置是否显示提示信息,true 表示显示信息,false 表示不显示信息。如果是将确定进度的进度条设置为显示信息,默认为当前任务完成的百分比,也可以通过方法 setString(String s) 设置指定的提示信息;如果将不确定进度的进度条设置为显示提示信息,则必须设置指定的提示信息,否则将出现填充面积和进度提示信息不匹配的不正确效果;
- 如果采用确定进度的进度条,进度条并不能自动获取任务的执行速度,不需通过方法 setValue(int n) 反复修改当前的执行速度,例如将入口参数设置为 88,则将显示为 88%;如果采用不确定进度的进度条,则需要在任务执行完成后将其设置为采用确定进度的进度条,并将任务的执行进度设置为 100%,或者是设置指定的提示已完成的信息;
1. 应用:使用进度条
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame {
public static void main(String args[]) {
Test frame = new Test();
frame.setVisible(true);
}
public Test() {
super();
getContentPane().setLayout(new GridBagLayout());
setTitle("Regino");
setBounds(100, 100, 500, 375);
setBounds(100, 100, 266, 132);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel label = new JLabel();
label.setForeground(new Color(255, 107, 87));
label.setFont(new Font("", Font.BOLD, 16));
label.setText("欢迎使用在线升级功能!");
final GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.gridx = 0;
getContentPane().add(label, gridBagConstraints);
final JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
progressBar.setString("升级进行中......");
final GridBagConstraints gridBagConstraints_1 = new GridBagConstraints();
gridBagConstraints_1.insets = new Insets(5, 0, 0, 0);
gridBagConstraints_1.gridy = 1;
gridBagConstraints_1.gridx = 0;
getContentPane().add(progressBar, gridBagConstraints_1);
final JButton button = new JButton();
button.setText("完成");
button.setEnabled(false);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
final GridBagConstraints gridBagConstraints_2 = new GridBagConstraints();
gridBagConstraints_2.insets = new Insets(5, 0, 0, 0);
gridBagConstraints_2.gridy = 2;
gridBagConstraints_2.gridx = 1;
getContentPane().add(button, gridBagConstraints_2);
new Progress(progressBar, button).start();
}
class Progress extends Thread {
private final int[] progressValue = {6, 18, 27, 39, 51, 66, 81,
100};
private JProgressBar progressBar;
private JButton button;
public Progress(JProgressBar progressBar, JButton button) {
this.progressBar = progressBar;
this.button = button;
}
public void run() {
for (int i = 0; i < progressValue.length; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.setValue(progressValue[i]);
}
progressBar.setIndeterminate(false);
progressBar.setString("升级完成!");
button.setEnabled(true);
}
}
}