Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

displaying rectangles efficiently...

 
Schuyler Goting
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been working on a component that uses a custom paintComponent() function that is rather complex. It can take upwards of a tenth of a second under fairly normal circumstances, and for that reason, I only call repaint() when I absolutely need to. (Meaning the display would actually change), but I have now added "drag selection" functionality to my component, and the constant repaint() calls in order to update the rectangle are making the program very very choppy.
Is there a way to calculate the "background" image when necessary, and then just repaint it like a normal image without the tons of processing required in my current paintComponent() function, to allow for a non-choppy display of a selection rectangle?
If anyone has done this, I would love to see some example code. I tried to find a decent way of accomplishing this, but could not come up with one.
Thanks for the help.
--Sky.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Absolutely; the steps are to
1) Draw into an "offscreen buffer" (an Image created for this purpose)
2) Copy it onto the screen in paint().
3) Draw your selection rectangles, or whatever, onto the screen on top of it.
Now you only need to update the offscreen buffer when the image should actually change.
Examples of this are everywhere. The first example I ever saw was the GraphLayout applpet demo from the JDK -- see $(JAVAHOME)/demo/applets/GraphLayout/Graph.java in your JDK installation. In that class, the offscreen buffer is used just to make the image appear all at once, so it's actually redrawn every time; in your case, you'd only want to redraw the offscreen image when necessary.
 
Schuyler Goting
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, thank you kindly, that was most useful.
--Sky.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!