根據(jù)進(jìn)度條,再結(jié)合Timer組件,下面將列舉一個(gè)實(shí)例。該實(shí)例主要是演示一個(gè)進(jìn)度條的動(dòng)作事件。其程序代碼如下所示:
publicclassBWFimplementsActionListener,ChangeListener{
JFramejf=null;
JProgressBarpb;
JLabellabel;
Timertimer;
JButtonb;
publicBWF(){
jf=newJFrame("博為峰教育");
jf.setSize(300, 200);
JPanelcontentPane=newJPanel();
jf.setContentPane(contentPane);
label=newJLabel(" ",JLabel.CENTER);
pb=newJProgressBar();
pb.setOrientation(JProgressBar.HORIZONTAL);
pb.setMinimum(0);//最小刻度
pb.setMaximum(100);//最大刻度
pb.setValue(0);
pb.setStringPainted(true);
pb.addChangeListener(this);//添加進(jìn)度條變化事件
pb.setPreferredSize(newDimension(200, 300));
JPanelpanel=newJPanel();
b=newJButton("開始");
b.addActionListener(this);
panel.add(b);
timer=newTimer(50,this);
contentPane.add(panel,BorderLayout.NORTH);
contentPane.add(pb,BorderLayout.CENTER);
contentPane.add(label,BorderLayout.SOUTH);
jf.setVisible(true);
jf.addWindowListener(newWindowAdapter() {
publicvoidwindowClosing(WindowEvente) {
System.exit(0);
}
});
}
publicstaticvoidmain(String[]args) {
newBWF();
}
@Override
publicvoidstateChanged(ChangeEvente) {
intvalue=pb.getValue();
if(e.getSource()==pb){
label.setText("目前已完成進(jìn)度:"+value+"%");
}
}
@Override
publicvoidactionPerformed(ActionEvente) {
if(e.getSource()==b){//單擊開始時(shí),計(jì)時(shí)開始
timer.start();
}
if(e.getSource()==timer){
intvalue=pb.getValue();
if(value<100){
value++;
pb.setValue(value);
}else{
timer.stop();
pb.setValue(0);
}
}
}
}