Razak
Razak

Reputation: 43

My program goes through the loop an unexpected amounts

As the header clarifies, a loop of mine that should only go through it 1 time (after toying with it, this made it the most obvious) goes through it twice, sometimes thrice.

It is weird, I cut out everything that confused me (still very new to java), but it doesn't change anything. So now I know that it has to do with the panel somehow, but I can not for the life of me figure out, what might be the issue. I even removed all getter and setters. Somehow that loop runs through 2-3 times. (originally I had it draw dots but after it showed some weird behaviour I tried to figure it out, since the code is just taken from an online tutorial) Even tried break; but no to no avail.

Here is my code:

public class drawDot extends JPanel {

    //GetterSetter gs = new GetterSetter();

    public void paintComponent(Graphics g) {
        //super.paintComponent(g);

        //Graphics2D g2d = (Graphics2D) g;

        //g2d.setColor(Color.black);
        // Random r = new Random();

        for (int i = 0; i <= 0;i++) {
            // int y = 50;
            //g2d.fillOval(gs.getX(), y, 30, 30);
            // gs.setX(gs.getX()+30);
            System.out.println("30");
            break; 
        }
    }

    public static void main(String[] args) {
        drawDot points = new drawDot();
        JFrame frame = new JFrame("Points");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(points);
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
   }

}

Upvotes: 0

Views: 46

Answers (1)

muasif80
muasif80

Reputation: 6006

Whenever your JPanel is repainted it will call the paintComponent. It can be repainted many times during the execution of your program.

You can create a static variable paintCounter in your class and then print it out in the loop along with the loop index to see how many times your loop is run during single invocation of the paintComponent.

private static paintCounter = 0;
public void paintComponent(Graphics g) {
    paintCounter = paintCounter + 1;

    for (int i = 0; i < 1; i++) {
        System.out.println("30");
        System.out.println("PaintComponent called " + paintCounter + " times, loop index " + i);
    }
}

Upvotes: 1

Related Questions