Getting my jProgressBar to run on a timer from 1 to 100

守給你的承諾、 提交于 2019-12-10 16:37:45

问题


I was looking through this thread

How to make Timer countdown along with progress bar?

I would like to add this to my code so i can just get a jProgressBar and a Button, (Using netbeans preferably)

So that when I hit the button it runs from 0 to 100 steadily, I really have tried to go at this on my own and have got really mad, any help would be nice.


回答1:


Leveraging @Andrew's example,

import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;

class CountUpProgressBar extends JPanel {

    private JProgressBar bar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
    private JLabel label = new JLabel("", JLabel.CENTER);
    private Timer timer = new Timer(100, new ActionListener() {

        private int counter = 1;

        @Override
        public void actionPerformed(ActionEvent ae) {
            label.setText(String.valueOf(counter));
            bar.setValue(++counter);
            if (counter > 100) {
                timer.stop();
            }
        }
    });

    CountUpProgressBar() {
        super.setLayout(new GridLayout(0, 1));
        bar.setValue(0);
        timer.start();
        this.add(bar);
        this.add(label);
        JOptionPane.showMessageDialog(null, this);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                CountUpProgressBar cdpb = new CountUpProgressBar();
            }
        });
    }
}


来源:https://stackoverflow.com/questions/11918384/getting-my-jprogressbar-to-run-on-a-timer-from-1-to-100

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!