Time Delay using Thread.sleep() for paintComponent(Graphics g) not working as expected

后端 未结 2 1202
长情又很酷
长情又很酷 2021-01-15 11:32

I am making an Animated ProgressBar, in which i used multiple fillRect() method of class javax.swing.Graphics.
To put a delay after each rectan

相关标签:
2条回答
  • 2021-01-15 11:51

    I really wouldn't do this. The Swing refresh thread isn't supposed to be used like this. You're much better off using another thread (perhaps using a TimerTask) and redrawing rectangles upon demand.

    Check out the Oracle ProgressBar tutorial for more info, code etc.

    0 讨论(0)
  • 2021-01-15 12:11

    Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeated tasks. See Concurrency in Swing for more details. Also be sure to check the progress bar tutorial linked by @Brian. It contains working examples.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    class DrawPanel extends JPanel
    {
        int i = 0;
        public DrawPanel() {
            ActionListener animate = new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    repaint();
                }
            };
            Timer timer = new Timer(50,animate);
            timer.start();
        }
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.setColor(new Color(71,12,3));
            g.fillRect(35,30,410,90);
    
            Color c = new Color (12*i/2,8*i/2,2*i/2);
            g.setColor(c);
            g.fillRect( 30+10*i,35,20,80);
    
            i+=2;
            if (i>40) i = 0;
        }
    }
    
    class ProgressBar
    {
        public static void main (String []args)
        {
            DrawPanel panel = new DrawPanel();
            JFrame app = new JFrame();
            app.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            app.add(panel);
            app.setSize(500,200);
            app.setVisible(true);
        }
    }
    
    0 讨论(0)
提交回复
热议问题