Search code examples
javaswingdelaypaint

Implementing a timer in java


 import java.awt.Graphics;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import javax.swing.JLabel;
 import java.awt.*;
 import javax.swing.*;
 import java.util.Timer;
 import java.awt.event.*;
 import java.awt.event.*;
 import javax.swing.*;

 class autos extends JLabel
 {
     @SuppressWarnings("serial")
     int z=100,i=50;
     public static void main(String[] args)
     {

         JFrame frame=new JFrame("Rectangle");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
         frame.setSize(1000,1000);
         frame.add(new autos());    
     }

    @Override
    public void paintComponent( Graphics g )
    {
        for(i=1;i<=7;i++)
        {
            g.drawRect(z,100,100,100);
            z=z+120;
            //timer delay
        }

    }
}

Hello,I'm trying to create a program in java that draws mre rectangles one after another with a delay(not all of them at once).

Since sleep and TimeUnit will freeze the paintComponent, I'm a bit clueless.I tried to use a timer to make a delay, but I failed.I cannot understand how to use the timer in this case.

How do I make a time delay between the rectangles?


Solution

  • You should start by taking a look at How to use Swing Timers and Concurrency in Swing

    You have to think of a Swing Timer as pseudo loop, which, every time it ticks, you update some value which, when your call repaint and your paintComponent method is called, you can update the UI appropriately

    Timer

    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class Test {
    
        public static void main(String[] args) {
            new Test();
        }
    
        public Test() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private int count = 0;
    
            public TestPane() {
                Timer timer = new Timer(500, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        count++;
                        if (count == 7) {
                            ((Timer)e.getSource()).stop();
                        }
                        repaint();
                    }
                });
                addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        timer.stop();
                        count = 0;
                        timer.start();
                    }
                });
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension((120 * 7) + 100, 300);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                super.paintComponent(g);
                int x = 100;
                for (int rect = 1; rect <= count; rect++) {
                    g2d.drawRect(x, 100, 100, 100);
                    x += 120;
                    //timer delay
                }
                g2d.dispose();
            }
        }
    }
    

    ps- Click the panel to get the timer to start