Search code examples
javaswingjscrollpaneinvalidation

How to paint only visible area of my custom control in Swing?


Suppose I have big custom control inscribed inside JScrollPane or clipped by other reasons. How to determine from within paintComponent() method which coordinates are to paint?


Solution

  • Take a look at Painting in AWT and Swing, it has an excellent explanation.

    But the general gist is, when your component is painted, its clipping rectangle is already set (nb need to check how this works for view ports, but I suspect its the same) to the visible area needing to be updated.

    You can check the clip rectangle of the Graphics context past to your paint method and determine what area you should update.