-1

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.stack.imgur.com/T8F0V.png

And afterwards it looks like this, https://i.stack.imgur.com/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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user3558410
  • 59
  • 1
  • 9
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). 2) For many components in one space, use a [`CardLayout`](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html) as seen in this [short example](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson May 14 '14 at 05:46
  • `public void paintComponent(Graphics g) { if(errors == 1)..` should be `public void paintComponent(Graphics g) { super.paintComponent(g); if(errors == 1)..` – Andrew Thompson May 14 '14 at 05:47

1 Answers1

1

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • That fixes it. Thanks! Who knew it could be that simple. – user3558410 May 14 '14 at 05:48
  • I'd also consider using a `switch` statement instead of an `if` statement and reverse the order in which the values are checked, this would allow you to keep count of the number of errors but reduce the amount of duplicated code you would need to produce in order to get the `if` statement to work – MadProgrammer May 14 '14 at 05:50