Java Reference
In-Depth Information
Figure 18-16.
Printing progress dialog box displayed by the printing tables example
Yes, it really is that easy to print a multiple-page table with JDK 5.0. The
print()
method
returns a
boolean
, so you can discover if the user canceled the operation.
For those looking for more control over the printing operation, there are several other
overloaded versions of the
print()
method of
JTable
. Like the simple
print()
method, they all
can throw a
PrinterException
.
One
print()
version lets you specify the print mode:
public boolean print(JTable.PrintMode printMode)
The
JTable.PrintMode
argument is an enumeration of
FIT_WIDTH
and
NORMAL
. When not
specified with the no-argument version of
print()
, the default is
FIT_WIDTH
.
Another version lets you specify a page header or footer:
public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat,
MessageFormat footerFormat)
MessageFormat
comes from the
java.text
package. The one argument to the header and
footer formatting string is the page number. To display the page number, include
{0}
in your
formatting string where you want the page number to appear. Both will appear centered on the
page, with the header in a larger font. To demonstrate, change the
print()
call in Listing 18-19
to the following (and add an
import
line):
MessageFormat headerFormat = new MessageFormat("Page {0}");
MessageFormat footerFormat = new MessageFormat("- {0} -");
table.print(JTable.PrintMode.FIT_WIDTH, headerFormat, footerFormat);
The final
print()
version is the all inclusive one, allowing you to not show the printer
dialog box and configure what the default print request attribute set entails, such as how many
copies to print.
public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat,
MessageFormat footerFormat, boolean showPrintDialog,
PrintRequestAttributeSet attr, boolean interactive)
For those times when you desire no user interaction to print, consider using this last version.