Hello,

I have a JFrame, inside which is a JPanel, in which I am drawing lines in the paintComponent() function at an interval of 1 second. The screen always freezes. How can I change the program below such that I can see the lines being drawn after every second?

Thank you!

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

public class LineDraw extends JPanel 
{
   
    private int number;

    
    LineDraw (int x)
    {
        number = x;

        
    }
    
    public void paintComponent (Graphics g)  
    {
            
            super.paintComponent(g);
            g.setColor(Color.RED);
            
          
             for (int y = 0;y<number;y+=10)
             {
                g.drawLine(y,40,380,30);
                try{
                      Thread.sleep(1000);
                    }
                catch (InterruptedException e)
                {}
             }
           
          
    }
    
   
}
import java.awt.*;
import javax.swing.*;

public class Screensaver
{
    public static void main(String args[])
    {
        JFrame frame = new JFrame("Screensaver v1");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        LineDraw linedraw = new LineDraw(120);

        frame.add(linedraw);
        frame.setSize(800,800);
        frame.setVisible(true);
       
    }
}

Use a Swing Timer to update the line coordinates and call repaint. You will need to make "y" a class variable and paintComponent() just needs to draw the line.

public void paintComponent (Graphics g)  
    {
       super.paintComponent(g);
       g.setColor(Color.RED);
       g.drawLine(y,40,380,30);
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.