Search code examples
javajpanelswitching

(JPanel switching ) add delay in seconds btween two panels switching (java)


I am trying to add delay between two JPanels switching on same JFrame, both are changing visibility type in loop. I also try thread.sleep but it not working thanks in advance :)

panel 1 color is red

panel 2 color is black

 for (int i = 0; i < LENGTH; i++) {
    panel1.setVisible(true)
/*************************************
   here i want to add delay 
**************************************/  
    panel1.setVisible(false)
    panel2.setVisible(true);
    for (int k = 0; k < rSIZE; k++) {
        tempr[i][k].setBackground(labelsGrid[i][k].getBackground());
    }
}

Solution

  • You need to use Swing Timers to trigger delays between your UI toggling. Here's a simple example.

    package app;
    
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    
    public class App extends JFrame
    {
        private JLabel label;
        private Timer timer;
        private int counter = 10; // the duration
        private int delay = 1000; // every 1 second
        private static final long serialVersionUID = 1L;
    
        public App()
        {
            super("App");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
    
            label = new JLabel("Wait for " + counter + " sec", JLabel.CENTER);
            JPanel contentPane = (JPanel) getContentPane();
            contentPane.add(label, BorderLayout.CENTER);
            contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            pack();
    
            ActionListener action = new ActionListener()
            {   
                @Override
                public void actionPerformed(ActionEvent event)
                {
                    if(counter == 0)
                    {
                        timer.stop();
                        label.setText("The time is up!");
                    }
                    else
                    {
                        label.setText("Wait for " + counter + " sec");
                        counter--;
                    }
                }
            };
    
            timer = new Timer(delay, action);
            timer.setInitialDelay(0);
            timer.start();
    
            setVisible(true);
        }
    
        public static void main(String[] args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    new App();
                }
            });
        }
    }
    

    This simple timer will trigger ActionListener every second and update label after decrementing counter values.