简体   繁体   中英

repaint() in loop only called once - Java

I am trying to draw a grid on a JPanel but when I call the repaint method inside a loop it works only once. Here is my code:

public class Board extends JPanel{

    // --- Set Density of Grid ---
    public final int lines = 10;
    // ---------------------------

    public final int width =  600;
    public final int height = 600;

    public Point p1 = new Point(0,0);
    public Point p2 = new Point(0,0);

    public Board() {


        int c0 = width/lines;
        for (int j=0; j<2; j++){
            int c1 = width/lines;
            for (int i=0; i<lines; i++){

                if (j==0){
                    p1 = new Point(c1,0);
                    p2 = new Point(c1,height);
                }

                if (j==1){
                    p1 = new Point(0,c1);
                    p2 = new Point(width,c1);
                }

                c1 = c1 + c0;

                repaint();

            }
        }
    }


    public void drawGrid(Graphics g){
        g.drawLine(p1.x, p1.y, p2.x, p2.y);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);

        drawGrid(g);
        System.out.println("Inside");
    }

}

this is the output:

Inside

How can I call the paintComponent method multiple times when I use for loop?

The repaint() method just makes a request to the RepaintManager to paint components. The RepaintManager will then consolidate multiple requests into a single painting of the component to make the painting more efficient. So because all your requests are made within nanoseconds of one another in your loop, they all get consolidated into a single request.

If you want animation of some kind then you need to use a Swing Timer to schedule the animation. So each time the Timer fires you would increment the indexes by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM