Sunday, July 17, 2011

Painting in Java

To perform painting in any component, we need to override the paint methods of the component. The painting process calls three overridable methods: paintComponent(Graphics g), paintChildren(Graphics g) and paintBorder(Graphics).

We generally override paintComponent method for painting the components. Since the painting in swing is carried out by Event Dispatcher Thread, there should be
some queuing mechanism to handle the requests. The event queue actually contains the queues of painting requests and the painting requests managed by RepaintManager by calling the paint method of the component to paint. In the first part, paintComponent method is called which paints own contents, and calls paintBorder which paints the border of the component and finally paints the children it contains by calling paintChildren method.

We can override paint(Graphics) too but we have to manage many other things like border of the control and child components the control contains. We use the Graphics object to paint on the component which is provided at the time of painting. For 2 dimensional painting, we generally cast the Graphics object into Graphics 2D object which can perform better for 2D painting. Since we render only part of the component, while other parts, we wanted to remain as it is. In that situation, we call the parent's paintComponent method and do our painting task so that there would not be undesired painting effects. We do not need to dispose the Graphics object because this object is referenced by other painting methods too. In some cases, we need to change the properties of Graphics object which is specific to a painting only, in such a scenario, we copy the Graphics object and do the painting , and after finishing the painting , we dispose the copy of Graphics object.

Double Buffering:
Double buffering is an indirect process of rendering in which the actual rendering
operations are not performed on the image displayed on the screen, rather an off-screen image(called back buffer) is used to create a rendered image and that image is copied to the screen. This process is repeated and the final result is the smoother display of the images on the screen.

No comments:

Post a Comment