java swing clipping problem

2019-08-30 10:09发布

问题:

I have a swing component which draws a fixed large (but fixed) vector image and overlays parts of the image with text which should display relative to the view port (not the absolute position) -- think frozen row labels in excel (illustrated below):

Header
 -- [some stuff] ----- [ some stuff] ----
Header2
 ----- [some stuff] ----- [ some stuff] ----

This works fine except when scrolling left to right. I try to set the clip bounds to the visible region in the paintComponent() method so that the entire viewport is always drawn -- however this does not appear to work:

public void paintComponent(Graphics graphics) {
  Graphics2D g = (Graphics2D)graphics;
  Shape oldClip = g.getClip();

  Rectangle clipBounds = getVisibleRect();
  g.setClip(clipBounds);

  drawMyImage();
  drawMyHeaders();

  g.setClip(oldClip);
}

However, this does not seem to work, I see the visible region is the right shape, but setting the clip has no effect. What can I do?

clip: java.awt.Rectangle[x=1762,y=0,width=57,height=182]    // clipped while scrolling
 vis: java.awt.Rectangle[x=1762,y=0,width=582,height=182]   // what I want to paint

回答1:

You aren't passing the graphics object into your headers, so they must be painting through something else which probably wont have your clipping shape set.

As commented, don't use setClip in paintComponent! The clipping region is used by Swing.

It seems what you want to do is have an overlay component layered above the scrolling component.