Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Java 2 introduces print capability to the Swing Forum - JavaWorld June 1999

Java 2 introduces print capability to the Swing Forum - JavaWorld June 1999

Tutorial Details:

Java 2 introduces print capability to the Swing Forum
Java 2 introduces print capability to the Swing Forum
By: By Michael Shoffner
Find out how to add Java 2's print functionality to your Swing-based apps
he Java 2 printing APIs give applications developers the ability to add print capabilities to Java applications and signed applets. The Java 2 printing system consists of a small number of interfaces and classes that encapsulate print-related entities such as printer jobs, page formats, printable pages, and collections of printable pages.
This month, we'll add Java 2 print capabilities to our old pal, the Swing Forum. But first we'll investigate the basics of the Java 2 printing system, including its operating principles and high-level features.
Java 2 printing basics
The Java 2 printing system offers applications the ability to print AWT text and graphics to any standard printer, whether networked or local. The printing system is a "callback" system, which means the system, not the printing application, drives the print process. In practice, this means the system determines the order in which pages are printed and makes callbacks into programmer-defined objects that know how to print pages. This architecture is similar to the 1.1 delegation event model and is highly analogous to the way component painting works.
The printing system consists of two entity types: job-control entities, which control printer jobs, and document-related entities, which represent documents to be printed as well as their constituent pages. The printing API is contained in the package java.awt.print .
Note : The Java 2 printing system should not be confused with the 1.1 printing system, although it is similar in some respects.
Job-control entities
Classes PrinterJob , PageFormat , and Paper are the job-control entities responsible for printer-job management.
The PrinterJob class encapsulates a printer job. PrinterJob operations include retrieving the default page format, popping up print- and page-format dialogs, and printing the job.
The PageFormat class represents a set of page-format settings. This class provides offset- and imageable-area information for use in rendering pages.
The Paper class represents the physical properties of a piece of paper in the printer. This class is used by the system and is not necessary for applications development.
In addition to the job-control entities described above, Java 2 printing makes use of document-related entities that provide both high level and low level document printing services, which we'll look at next.
Document-related entities
Document-related entities can be classified as either high level or low level. Pageable and Book are considered high level. In contrast, Printable "page painters" are low level.
High-level document-related entities represent whole documents, such as a resume, a book, or any other collection of printable pages.
A document is a collection of pages in which each page or group of pages may have different formats. For example, a business letter might consist of a "first page" that displays letterhead and standard header information and the beginning of the letter's text. This page may be followed by a series of additional pages containing the rest of the letter's text.
The Pageable interface provides applications developers with high-level document-related services. The Java 2 API supplies the Book class, which is an implementation of Pageable , so that developers don't have to write an implementation from scratch.
Book allows the developer to create an ordered list of document sections. Each document section consists of an instance of PageFormat associated with a page painter (see below) and an int that specifies the number of pages in the section.
Book s are used by appending groups of pages to them. Here's the correct syntax:
book.append (Printable painter, PageFormat pageFormat, int numpages);
High-level document-related entities make use of low-level entities to do the actual work of printing pages.
A low-level page painter is an object that knows how to render a single kind of page. It implements the Printable interface, which has one method:
public int print (Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException
When the system calls this method on the page painter object, the page painter's implementation will render the page specified by pageIndex , using the page format object pageFormat . Supplied graphics context rendering and component painting are done in exactly the same way.
The application doing the printing may use multiple page painters, each of which knows how to render a different kind of page. For example, most documents have a title page, table of contents, and pages of content. Each of these page types could have an associated page painter, which would be collected in a Pageable implementation, such as an instance of Book .
A single page painter can render multiple pages of the same type. In this case, the painter is responsible for rendering each page as it is requested by the system. The system may request pages in order or out of order, and it may request the same page more than once.
Printable jobs versus pageable jobs
A given printer job, represented by an instance of PrinterJob , can be either printable or pageable.
Printable jobs are simple jobs that consist of a single page painter. As noted above, a single page painter can paint multiple pages, in which case the system keeps calling the painter's print () method until the method returns Printable.NO_SUCH_PAGE .
Pageable jobs represent documents. Pageable jobs can consist of multiple page formats, each associated with a Printable page painter. Pageable jobs also have the advantage of allowing the system to find out in advance the number of pages in the document, so that the user can choose which pages to print by means of the print dialog.
The application specifies the type of printer job it wants by using one of the following two calls on the PrinterJob object ( job is used as an example):
job.setPrintable (Printable painter);
job.setPageable (Pageable document);
Now that we understand the Java 2 printing system, it's almost time to apply our knowledge -- but first, a quick peek at the Swing Forum.
Swing Forum basics
If you'll recall, the Swing Forum is a simple client/server discussion-forum system in which the client is implemented using Swing. The Swing Forum uses a JTree to allow users to access discussion threads and messages within those threads.
Swing Forum articles are encapsulated in the ForumArticle class and are stored as user objects aggregated by nodes in the tree. To get the instance of ForumArticle associated with a node, the following incantation is used (when the article is selected from the tree by the user):
ForumArticle art = (ForumArticle) node.getUserObject ();
The client display area used to display messages for reading is a TextArea class. After the user selects an article from the tree and the application obtains the correct instance of ForumArticle , the application sets the display area's text to the article text stored in the ForumArticle :
readArea.setText (art.getText ());
We're now ready to add message printing functionality to the Swing Forum.
Add printing to the Swing Forum
With the addition of message printing, Swing users can print either a selected article or all the articles in a message thread, simply by selecting the appropriate node in the tree and then selecting File-Print Current from the menu bar.
To add print functionality, we'll define a new menu item and event handler, a print-management helper method, a page painter for forum articles, and a Thread subclass to do the printing in a nonblocking fashion.
The five steps of this process are as follows:
Step 1. Add a new action
printCurrentAction = new AbstractAction ("Print Current Article") {
public void actionPerformed (ActionEvent e) {
printCurrentArticle ();
}
};
Step 2. Add the action to the menu bar
void layOutMenuBar () {
menubar = new JMenuBar ();
JMenu m = new JMenu ("File");
m.add (closeAction);
m.add (printCurrentAction);
...
Step 3. Create the printCurrent () method
The SwingForum class uses the printCurrent () method to kick off the printing process when the user actuates the process from the menu:
synchronized void printCurrent () {
// print based on the currently selected node
TreePath path = tree.getSelectionPath ();
if (path == null) {
// nothing selected
return;
}
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode) path.getLastPathComponent ();
int depth = path.getPathCount ();
ArrayList list = new ArrayList ();
if (depth == 2) {
// node is a thread
Enumeration children = node.children ();
while (children.hasMoreElements ()) {
DefaultMutableTreeNode child;
child = (DefaultMutableTreeNode) children.nextElement ();
list.add (child.getUserObject ());
}
} else if (depth == 3) {
// node is an article
list.add (node.getUserObject ());
}
if (list.size () > 0) {
// do the actual printing in another thread
new PrintingThread (list).start ();
}
}
The printCurrent () method first determines if a valid selection (thread or article) has been made. If so, it adds the selected ForumArticle instance(s) to an ArrayList . If the list turns out to have items in it, printCurrent () creates and starts a new PrintingThread object, and then passes in the list.
Note that since the items backing the list are immutable (an article object is never modified after it has been created), there is no need to clone the list to put it in another thread. Even in the unlikely event that the backing article object disappears from the tree (say, because the server removes the article and the client refreshes from the server while the print is in progress), the article object will still exist in the list until the printing thread goes out of scope.
Step 4. Create the PrintingThre


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Java 2 introduces print capability to the Swing Forum - JavaWorld June 1999

View Tutorial:
Java 2 introduces print capability to the Swing Forum - JavaWorld June 1999

Related Tutorials:

Java Tip 72: Press Escape to close your Swing dialog windows
Java Tip 72: Press Escape to close your Swing dialog windows
 
Implement a J2EE-aware application console in Swing
Implement a J2EE-aware application console in Swing
 
Master J2ME for live data delivery
Master J2ME for live data delivery
 
Discover and publish Web services with JAXR
Discover and publish Web services with JAXR
 
Take command of your software
Take command of your software
 
Eclipse casts shadows
Eclipse casts shadows
 
Speed up your Swing GUI construction with better building blocks
Speed up your Swing GUI construction with better building blocks
 
Sun boosts
Sun boosts enterprise Java
 
A first look at JavaServer Faces, Part I
A first look at JavaServer Faces, Part Learn how to implement Web-based user interfaces with JSF
 
Enhance your J2EE presentation layer
Enhance your J2EE presentation layer
 
Interesting ...
Interesting ...
 
Java on Apple IIc
Java Now Running on Apple IIc I strongly believe in WORA. Java is able to run on a lot of devices, from the credit card to the server. Today I\'m pleased to announce the availability of Java(tm) [1] on the Apple II family [2]. This runtime is a partial
 
Java theory and practice: Kill bugs dead
Inspection tools like FindBugs provide a second layer of defense against common coding errors.
 
JPOX Java Persistent Objects JDO
Presenting JPOX With a versatile and high performance implementation, JPOX is on the cutting edge of the available Java Data Objects (JDO) implementations, offering a free and full compliant JDO implementation released under an open source license.
 
Wi.Ser (WidgetServer) unified rich client framework
Wi.Ser is a Java/XML server-side GUI-framework which enables an application to run as either a monolithic Swing application, a thin-client/server Swing application, or as a Web application without any change!
 
InfoNode (Java Components)
InfoNode Docking Windows is a pure Java Swing based docking windows framework. The best way to see features of InfoNode Docking Windows is to try the Web Start demos.
 
Ease Swing development with the TableModel Free framework
This article introduces the TableModel Free (TMF) framework which eliminates the need to use TableModels with Swing JTables. The TMF framework allows for more configurable JTables by moving all of table-specific data outside of the compiled code and into
 
Hibernate simplifies inheritance mapping.
Learn three easy-to-implement strategies to map class hierarchies. Hibernate is an object-relational mapping and persistence framework that provides a lot of advanced features, ranging from introspection to polymorphism and inheritance mapping.
 
J2ME Technology Turns 5!
In 2004 the Java 2 Platform, Micro Edition (J2ME) celebrated its fifth anniversary. This article presents where J2ME is today.
 
Sanssouci is a Java framework for autogenerating fancy Swing-GUIs via introspection.
Sanssouci is a Java framework for autogenerating fancy Swing-GUIs via introspection which display objects directly to the user
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.