Java Reference
In-Depth Information
Printing Swing Components
Printing components is easier than you might think. Swing components are particularly easy to print
because they already know how to draw themselves. You should not call a Swing component's
paint()
method when you want to print it though. Rendering of Swing components is buffered by
default to improve the efficiency of displaying them but printing one by calling its
paint()
method
adds a lot of unnecessary overhead to the printing operation. Instead you should call the
print()
method that is defined in the
JComponent
class. This will render the component directly to the
graphics context that is passed as an argument, so there is no buffering of the output. The method
automatically prints any child components that the component contains, so you only need to call
print()
directly for a top-level component.
The
print()
method for a Swing component that has
JComponent
as a base calls three protected
methods to actually carry out the printing:
printComponent(Graphics g)
Prints the component.
printBorder(Graphics g)
Prints the component border.
printChildren(Graphics g)
Prints components that are children of the
component.
If you want to customize how a Swing component is printed you can subclass the component and override
any or all of these. This doesn't apply to a
JFrame
component though. The
JFrame
class is a subclass of
Frame
and does not have
JComponent
as a superclass. However, you can still call the
print()
method for
a
JFrame
component to print it. In this case it's inherited from the
Container
class.
Let's implement a capability to print the Sketcher application window to see how this can be done.
Try It Out - Printing the Sketcher Window
First we will add a menu item to the
Fi
le
menu in Sketcher to print the window. We will define this
using an instance the
FileAction
class:
saveAsAction = new FileAction("Save As...", "Save as new file");
printAction = new FileAction("Print",
KeyStroke.getKeyStroke('P',Event.CTRL
_
MASK), "Print sketch");
printWindowAction = new FileAction("Print window",
KeyStroke.getKeyStroke('W',Event.CTRL
_
MASK), "Print current window");
addMenuItem(fileMenu, newAction);
addMenuItem(fileMenu, openAction);
fileMenu.addSeparator(); // Add separator
addMenuItem(fileMenu, saveAction);
addMenuItem(fileMenu, saveAsAction);
fileMenu.addSeparator(); // Add separator
addMenuItem(fileMenu, printAction);
addMenuItem(fileMenu, printWindowAction);
// Rest of the code as before...