博為峰Java技術(shù)文章 ——JavaSE Swing 如何使用時(shí)間組件TimerⅡ

博為峰小博老師

根據(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);

}

}

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容