Java Reference
In-Depth Information
is no buffering of the output. The method automatically prints any child components that the component
contains, so you need to call
print()
directly only 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. The
printComponent()
method prints the component, the
printBorder()
method prints the component border, and the
printChildren()
method prints components
that are children of the component. They each have a
Graphics
parameter.
If you want to customize how a Swing component is printed, you can subclass the component and over-
ride 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
You can set up a menu item for this in the
createFileMenu()
method in the
SketcherFrame
class:
private void createFileMenu() {
JMenu fileMenu = new JMenu("File"); // Create File
menu
fileMenu.setMnemonic('F'); // Create
shortcut
createFileMenuActions(); // Create
Actions for File menu item
// Code to create print setup menu item...
// Menu item to print the application window
JMenuItem printWindowItem = new JMenuItem("Print Window");
printWindowItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(printer == null) {
JOptionPane.showMessageDialog(SketcherFrame.this,
"No default printer
available.",
"Printer Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// The app window is the page source
printJob.setPrintable(SketcherFrame.this,
pageFormat);
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println(pe);