简体   繁体   中英

Why is paintComponent() getting called multiple times?

Im trying to write a class implementing the observer interface, this class draws rectangles vertically according to the inputs from the textField. Everything run normally except my rectangles did not start from coord(0, 0). I tried to put a System.out.print and see what is going on, and it seems like my paintComponent() is called twice. I couldn't figure out where went wrong exactly. Can anyone please help me solve this problem? Below is my code:

public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        for (int i = 0; i < dm.getData().size(); i++)
        {
            Rectangle2D rectangle = new Rectangle2D.Double(x, y, dm.getDataElement(i), height);
            g2.draw(rectangle);
            System.out.println(i + "th rec drew.");
            y = y + height;
        }
    }

public void update(Observable o, Object arg) {
        // TODO Auto-generated method stub
        repaint();
    }

Swing GUI painting is never under your direct control. The painting may be done because your program requests that it be done, by say calling repaint() , and even that is not guaranteed to cause painting, or because the operating system believes a window needs repainting and directs it to do so. It is for this reason that you should avoid putting program logic, state-changing code such as y = y + height; , within a painting method. Place that elsewhere, say in your update(...) method or a Swing Timer, and then let the painting method be only responsible for drawing the visual representation of your program's state, not for changing it.

For greater detail on this, please read Painting in AWT and Swing

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