paintComponent is executing twice

后端 未结 2 1789
感动是毒
感动是毒 2020-12-21 11:59

This is bothering me, my code works and runs but when I went to run it, it seems to be looping my for loops twice, can anyone help me with my logic? Thanks...



        
2条回答
  •  星月不相逢
    2020-12-21 12:38

    Calling setPreferredSize() and pack() will cause paintComponent() to be called twice because the display needs to be redrawn for each call.

    Try removing pack() and move set size to the bottom, like this:-

    public Main() {
        Random g = new Random();
    
        //setPreferredSize(...); // commented this line
    
        for (int i = 0; i < radius.length; i++) {
            radius[i] = g.nextInt(50) + 1;
            xArray[i] = g.nextInt(250) + 1;
            yArray[i] = g.nextInt(150) + 1;
        }
    }
    
    public void paintComponent(Graphics page) {
            ...
    }
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("Circles");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        frame.setSize(300, 200); // added this line
    
        frame.getContentPane().add(new Main());
    
        // frame.pack(); // commented this line
    
        frame.setVisible(true);
    }
    

    This should work properly now.

提交回复
热议问题