1

I'm having some troubles with setClip in Java. I have a class that extends JPanel. Within that class I have overridden the paintComponent method. My paintComponent method looks something like this:

paintComponent {
    //draw some lines here
    Rectangle whole = g2.getClipBounds();//g2 is my Graphics2D object
    Rectangle part = <some rectangle that is a part of the whole paintable area>;
    g2.setClip(part);
    //draw some more stuff here
    g2.setClip(whole);
}

The problem that I'm seeing is that the area in the clipped region seems to be painted repeatedly. For example, if I tell it to paint, it paints just fine. But then, if I switch windows or somehow else cause it to paint the same thing again, the clipped region isn't cleared while the rest is. This results in the painting on the clipped region to appear bolder than the rest of the paintable area.

I imagine that I'm missing something in how setClip works.

Any suggestions would be much appreciated. Thanks in advance for any help.

Ryan
  • 4,517
  • 7
  • 30
  • 34
  • `setClip` is almost never what you want. Usually you should be making the clip region smaller rather than replacing it. IIRC, last time I looked all the uses of it in Swing were bugs. – Tom Hawtin - tackline Oct 06 '09 at 18:45
  • So does that mean that the first setClip is fine (because it's reducing the clip region), but the second setClip should be replaced? How do you reset the clip region. I've seen some places suggest using setClip(null) to reset the clip region, but that doesn't help me. – Ryan Oct 06 '09 at 19:23
  • When the `Graphics` object comes to you it may already have a clip region set. You should honour that clipping. – Tom Hawtin - tackline Oct 06 '09 at 19:36
  • 2
    (There are other clip methods. You can also create a `Graphics` object from a `Graphics` object, and just go back to the original to "remove" the clip (remember to dispose of any `Graphics` objects you create).) – Tom Hawtin - tackline Oct 06 '09 at 19:37

1 Answers1

2

Creating a new Graphics object from the old one did the trick for me, as adviced by Tom.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Ryan
  • 4,517
  • 7
  • 30
  • 34