How to make Timer countdown along with progress bar?

前端 未结 3 1613
迷失自我
迷失自我 2020-12-11 22:14

How can I make it so that the progress bar slowly goes down with the time limit?

class GamePanel extends JPanel implements MouseListener, ActionListener
{
           


        
3条回答
  •  悲&欢浪女
    2020-12-11 23:05

    Sorry, I still could not find the motivation to actually read your code, but just threw together this example based on the question. See if it gives you some ideas.

    Note that it is an SSCCE and uses just 40 lines of code in all.

    import java.awt.event.*;
    import javax.swing.*;
    
    class CountDownProgressBar {
    
        Timer timer;
        JProgressBar progressBar;
    
        CountDownProgressBar() {
            progressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 10);
            progressBar.setValue(10);
            ActionListener listener = new ActionListener() {
                int counter = 10;
                public void actionPerformed(ActionEvent ae) {
                    counter--;
                    progressBar.setValue(counter);
                    if (counter<1) {
                        JOptionPane.showMessageDialog(null, "Kaboom!");
                        timer.stop();
                    } 
                }
            };
            timer = new Timer(1000, listener);
            timer.start();
            JOptionPane.showMessageDialog(null, progressBar);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater( new Runnable() {
                public void run() {
                    CountDownProgressBar cdpb = new CountDownProgressBar();
                }
            });
        }
    }
    

提交回复
热议问题