java swing 製作進度條– 類比卸載,附效果圖

來源:互聯網
上載者:User

    利用timer和progressbar外加兩個按鈕製作的小程式,點擊start按鈕開始卸載,點擊stop停止。

代碼如下:


-----------------------------------------------以下是代碼區--------------------------------------------------------------------------

import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JProgressBar;import javax.swing.Timer;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;public class ProgressBar extends JFrame implements ChangeListener,ActionListener {JButton start, stop;JProgressBar bar;JLabel show;JPanel pane, pane1;Timer timer;public ProgressBar(String title) {super(title);init();pack();}public void init() {setBounds(300, 100, 300, 100);pane = new JPanel();pane.setLayout(new BorderLayout());getContentPane().add(pane);start = new JButton("start");start.addActionListener(this);stop = new JButton("stop");stop.addActionListener(this);pane1 = new JPanel();pane1.add(start);pane1.add(stop);bar = new JProgressBar();bar.setMinimum(0);bar.setMaximum(100);bar.setValue(100);bar.setStringPainted(true);bar.addChangeListener(this);bar.setPreferredSize(new Dimension(200, 30));int leave = 100 - bar.getValue();show = new JLabel("已完成:" + leave, JLabel.CENTER);pane.add(pane1, BorderLayout.NORTH);pane.add(bar, BorderLayout.CENTER);pane.add(show, BorderLayout.SOUTH);timer = new Timer(50, this);}@Overridepublic void stateChanged(ChangeEvent e) {// TODO Auto-generated method stubint value = bar.getValue();int leave = 100 - value;if (e.getSource() == bar) {show.setText("已完成:" + leave + "%");}}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource() == start) {timer.start();} else if (e.getSource() == stop) {timer.stop();bar.setValue(0);} else if (e.getSource() == timer) {int value = bar.getValue();if (value > 0) {value--;bar.setValue(value);}}}public static void main(String[] args) {new ProgressBar("uninstall").setVisible(true);}}

------------------------------------------------------以上是代碼區------------------------------------------------------------------------------


運行效果如下:

     ---------》  ------------》

註:本代碼可以直接copy運行




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.