Search code examples
javaswingjpanelpaintcomponent

Panel.repaint(); messes up layout


JPanel Initiation

    p = new JPanel() {
        private static final long serialVersionUID = 1L;
        public void paintComponent(Graphics g) {
            if(errors == 1)
                g.drawOval(215, 50, 75, 75);
            else if(errors == 2)
                g.drawOval(200,200,200,200);
        }
    };

Method that calls repaint

static void drawHead() {
    System.out.println("Head");
    errors = 1;
    p.removeAll();
    p.revalidate();
    p.repaint();
}

Before repaint my frame looks like this, https://i.sstatic.net/T8F0V.png

And afterwards it looks like this, https://i.sstatic.net/UFwr0.png

I'm thinking there is an error in my drawHead() method but I cannot seem to resolve the issue. Does anyone know what is going on? My desired outcome would be the first image, but with a head drawn in.


Solution

  • You've broken the paint chain by failing to call super.paintComponent first before you performed any custom painting

    Graphics is shared resource, every component painted in a during a paint cycle will share the same Graphics context, this means that whatever was previously painted to the Graphics context will remain unless you clear it.

    One of the jobs of paintComponent is to prepare the Graphics context for painting by filling it with the background color of the component