Site iconJava PDF Blog

Drawing Java Components without displaying them.

Recently I have had a need to draw a pdf page to a provided graphics object. Considering that we draw the page to a Panel this is no hard feat to achieve all we need is to pass the graphics object into the Panels paint method. The problem we have run into is that we need to do this without displaying the Panel itself.

For most of the pages content this is no problem and the output is correct. Form components on the other hand are not so simple. By default our form components are swing components added to the Panel so as to appear at the correct point on the page. Where we have custom appearances we can override the display of the components.

When passing in a provided graphics object everything appears to be rendered correctly but some forms are not displayed correctly, they appear as empty grey boxes on the page. I have spent some time looking into this and I have come to learn several important lessons.

So, what is the difference between displayable and visible. A visible component is currently visible on the screen. A displayable component means it has been added to a containment hierarchy that has been made displayable. This can be done by either calling pack() on the ancestor window or by making the ancestor visible.

So in order to allow the pdf page to be drawn to a graphics object and have all the form components appear correctly without displaying the pages to screen we need to add the form components to a dummy frame. By adding the form components to a JFrame and then calling pack() from the JFrame we can mark the for components and any children components as displayable.

Problem solved.