Printing PrintGraphics Interface

Similar documents
16.1 DataFlavor DataFlavor Methods. Variables

How to create PDF maps, pdf layer maps and pdf maps with attributes using ArcGIS. Lynne W Fielding, GISP Town of Westwood

NTFS permissions represent a core part of Windows s security system. Using

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

5544 = = = Now we have to find a divisor of 693. We can try 3, and 693 = 3 231,and we keep dividing by 3 to get: 1

What you should know about: Windows 7. What s changed? Why does it matter to me? Do I have to upgrade? Tim Wakeling

The number of parameters required for authoring an ipart depends on the type of the part you are publishing.

ACCESS Importing and Exporting Data Files. Information Technology. MS Access 2007 Users Guide. IT Training & Development (818)

An Introduction to Excel Pivot Tables

Xerox DocuPrint P12 Print Driver User Guide

Copyright 2008 The Pragmatic Programmers, LLC.

How to test and debug an ASP.NET application

Content Author's Reference and Cookbook

NICK COLLIER - REPAST DEVELOPMENT TEAM

Processing an Actual Journal Entry UCD Campuses

If you know exactly how you want your business forms to look and don t mind

Statgraphics Getting started

Why should I back up my certificate? How do I create a backup copy of my certificate?

Tutorial 1: The Freehand Tools

Session 7 Fractions and Decimals

Figure 3.5: Exporting SWF Files

Programming Methods & Java Examples

Excel Formatting: Best Practices in Financial Models

Finding Job Openings on the Internet. A Special Report

The Basic Java Applet and JApplet

Microsoft PowerPoint Exercises 4

Approach of Unit testing with the help of JUnit

Using Microsoft Word. Working With Objects

Using Mail Merge in Microsoft Word 2003

Excel macros made easy

C# and Other Languages

Equations, Lenses and Fractions

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

HTML Code Generator V 1.0 For Simatic IT Modules CP IT, IT, IT

Creating and Using Data Entry Forms

1 Hour, Closed Notes, Browser open to Java API docs is OK

WRITING PROOFS. Christopher Heil Georgia Institute of Technology

Measuring the Impact of Volunteering

Working with sections in Word

INSTALL NOTES Elements Environments Windows 95 Users

The Power of Relationships

G10 Data Setting Command

13 Classes & Objects with Constructors/Destructors

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

Example Chapter 08-Number 09: This example demonstrates some simple uses of common canned effects found in popular photo editors to stylize photos.

Fundamentals of Java Programming

How to resize, rotate, and crop images

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Create a report with formatting, headings, page numbers and table of contents

Custom Linetypes (.LIN)

Club Accounts Question 6.

Business Objects InfoView Quick-start Guide

Sample Cover Letter Format

Q&As: Microsoft Excel 2013: Chapter 2

Tips and Tricks for Printing an Excel Spreadsheet

HOW TO SELECT A SCIENCE FAIR TOPIC

Crop and Frame Your Photos

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Philosophical argument

Introduction to Microsoft Excel 2010

COMBINING FILES IN PDF PORTFOLIOS

Hypercosm. Studio.

Using Microsoft Project 2000

Getting Started with WebSite Tonight

Microsoft Migrating to Word 2010 from Word 2003

Microsoft Excel 2013 Tutorial

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

Part 3: GridWorld Classes and Interfaces

Tutorial: Getting Started

SECTION 5: Finalizing Your Workbook

Level Lesson Plan Session 1

Design Your Own T-Shirt Page 1

How To Write A Program For The Web In Java (Java)

PostScript User Guide 604P17454_EN

Microsoft Word 2010 Mail Merge (Level 3)

Understanding Operating System Configurations

Named Memory Slots. Properties. CHAPTER 16 Programming Your App s Memory

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Programming with Data Structures

Migrating to Excel 2010 from Excel Excel - Microsoft Office 1 of 1

Live Agent for Support Agents

CmpSci 187: Programming with Data Structures Spring 2015

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

5. Tutorial. Starting FlashCut CNC

Dreamweaver and Fireworks MX Integration Brian Hogan

2Creating Reports: Basic Techniques. Chapter

Using VLOOKUP to Combine Data in Microsoft Excel

6 BEST SOCIAL SELLING TECHNIQUES TO HELP YOU MOVE THE CONVERSATION NEEDLE

Reading and Understanding Java s API Documentation

Completing a Quiz in Moodle

Decision Making under Uncertainty

Java and JavaScript. Krishna Tateneni

Inventory Computers Using TechAtlas for Libraries

Unit 4 i5/os Work Management

Table of Contents User Guide... 1 Welcome... 4 Front End Life Blue... 5 General Navigation... 5 Menu Bar... 5 Continuous Scroll... 5 Hyperlinks...

Invalidity in Predicate Logic

Hello. What s inside? Ready to build a website?

Importing PDF Files in WordPerfect Office

Transcription:

In this chapter: PrintGraphics Interface PrintJob Class Component Methods Printing Example Printing Arbitrary Content 17 Printing Java 1.1 introduces the ability to print, a capability that was sadly missing in Java 1.0, even though the Component class had print() and printall() methods. However, it is possible to print arbitrary content, including multipage documents. The printing facility in Java 1.1 is designed primarily to let a program print its display area or any of the components within its display. Printing is implemented with the help of one public interface, PrintGraphics, and one public class, PrintJob, of AWT. The real work is hidden behind classes provided with the toolkit for your platform. On Windows NT/95 platforms, these classes are sun.awt.windows.wprintgraphics and sun.awt.windows.wprintjob. Other platforms have similarly named classes. Printing from an applet has security implications and is restricted by the SecurityManager. It is reasonable to suppose that a browser will make it possible to print a page containing an applet; in fact, Netscape has done so ever since Navigator 3.0. However, this ability might not take advantage of Java s printing facility. It isn t reasonable to suppose that an applet will be able to initiate a print job on its own. You might allow a signed applet coming from a trusted source to do so, but you wouldn t want to give any random applet access to your printer. (If you don t understand why, imagine the potential for abuse.) 17.1 PrintGraphics Interface Printing is similar to drawing an object on the screen. Just as you draw onto a graphics context to display something on the screen, you draw onto a printing context to create an image for printing. Furthermore, the printing context and 513

514 CHAPTER 17: PRINTING graphics context are very closely related. The graphics context is an instance of the class Graphics. The printing context is also an instance of Graphics, with the additional requirement that it implement the PrintGraphics inter face. Therefore, any methods that you use to draw graphics can also be used for printing. Furthermore, the paint() method (which a component uses to draw itself on the screen) is also called when a component must draw itself for printing. In short, to print, you get a special Graphics object that implements the Print- Graphics inter face by calling the getgraphics() method of PrintJob (discussed later in this chapter) through Toolkit. You then call a component s print() or printall() method or a container s printcomponents() method, with this object as the argument. These methods arrange for a call to paint(), which can draw on the printing context to its heart s content. In the simple case where you re just rendering the component on paper, you shouldn t have to change paint() at all. Of course, if you are doing something more complex (that is, printing something that doesn t look exactly like your component), you ll have to modify paint() to determine whether it s painting on screen or on paper, and act accordingly. The code would look something like this: public void paint(graphics g) { if (g instanceof PrintGraphics) { // Printing else { // Painting If the graphics object you receive is an instance of PrintGraphics, you know that paint() has been called for a print request and can do anything specific to printing. As I said earlier, you can use all the methods of Graphics to draw on g. If you re printing, though, you might do anything from making sure that you print in black and white to drawing something completely different. (This might be the trick you use to print the contents of a component rather than the component itself. However, as of Java 1.1, it s impossible to prevent the component from drawing itself. Remember that your paint() method was never responsible for drawing the component; it only drew additions to the basic component. For the time being, it s the same with printing.) When you call printcomponents() on a Container, all the components within the container will be printed. Early beta versions of 1.1 only painted the outline of components within the container. The component should print as it appears on the screen.

17.2 PRINTJOB CLASS 515 17.1.1 Methods public abstract PrintJob getprintjob () The getprintjob() method returns the PrintJob instance that created this PrintGraphics instance. This seems like circular logic: you need a PrintJob to create a PrintGraphics object, but you can get a PrintJob only from a PrintGraphics object. To break the circle, you can get an initial PrintJob by calling the getprintjob() method of Toolkit. getprintjob() looks like it will be useful primarily within paint(), where you don t have access to the original PrintJob object and need to get it from the graphics context. System-provided PrintGraphics objects inherit their other methods from the Graphics class, which is discussed in Chapter 2, Simple Graphics. * The one method that s worth noting here is dispose(). In a regular Graphics object, calling dispose() frees any system resources the object requires. For a PrintGraphics object, dispose() sends the current object to the printer prior to deallocating its resources. Calling dispose() is therefore equivalent to sending a form feed to eject the current page. 17.2 PrintJob Class The abstract PrintJob class provides the basis for the platform-specific printing subclasses. Through PrintJob, you have access to properties like page size and resolution. 17.2.1 Constructor and Pseudo -Constructor public PrintJob () The PrintJob() constructor is public; however, the class is abstract, so you would never create a PrintJob instance directly. Since you can t call the PrintJob constructor directly, you need some other way of getting a print job to work with. The proper way to get an instance of PrintJob is to ask the Toolkit, which is described in Chapter 15, Toolkit and Peers. The get- PrintJob() method requires a Frame as the first parameter, a String as the second parameter, and a Properties set as the third parameter. Here s how you might call it: * Anything can implement the PrintGraphics inter face, not just subclasses of Graphics. However, in order for paint() and print() to work, it must be a subclass of Graphics.

516 CHAPTER 17: PRINTING PrintJob pjob = gettoolkit().getprintjob(aframe, "Job Title", (Properties)null); The Frame is used to hold a print dialog box, asking the user to confirm or cancel the print job. (Whether or not you get the print dialog may be platform specific, but your programs should always assume that the dialog may appear.) The String is the job s title; it will be used to identify the job in the print queue and on the job s header page, if there is one. The Properties parameter is used to request printing options, like page reversal. The property names, and whether the requested properties are honored at all, are platform specific. UNIX systems use the following properties: awt.print.printer awt.print.papersize awt.print.destination awt.print.orientation awt.print.options awt.print.filename awt.print.numcopies Windows NT/95 ignores the properties sheet. If the properties sheet is null, as in the previous example, you get the system s default printing options. If the properties sheet is non-null, getprintjob() modifies it to show the actual options used to print the job. You can use the modified properties sheet to find out what properties are recognized on your system and to save a set of printing options for use on a later print job. If you are printing multiple pages, each page should originate from the same print job. According to Sun s documentation, getprintjob() ought to return null if the user cancels the print job. However, this is a problem. On some platforms (notably Windows NT/95), the print dialog box doesn t even appear until you call the get- Graphics() method. In this case, getprintjob() still returns a print job and never returns null. If the user cancels the job, getgraphics() returns null. 17.2.2 Methods public abstract Graphics getgraphics () The getgraphics() method returns an instance of Graphics that also implements PrintGraphics. This graphics context can then be used as the parameter to methods like paint(), print(), update(), or printall() to print a single page. (All of these methods result in calls to paint(); in paint(), you draw whatever you want to print on the Graphics object.)

17.3 COMPONENT METHODS 517 On Windows NT/95 platforms, getgraphics() returns null if the user cancels the print job. public abstract Dimension getpagedimension () The getpagedimension() method returns the dimensions of the page in pixels, as a Dimension object. Since getgraphics() returns a graphics context only for a single page, it is the programmer s responsibility to decide when the current page is full, print the current page, and start a new page with a new Graphics object. The page size is chosen to roughly represent a screen but has no relationship to the page size or orientation. public abstract int getpageresolution () The getpageresolution() method returns the number of pixels per inch for drawing on the page. It is completely unclear what this means, since the number returned has no relationship to the printer resolution. It appears to be similar to the screen resolution. public abstract boolean lastpagefirst () The lastpagefirst() method lets you know if the user configured the printer to print pages in reverse order. If this returns true, you need to generate the last page first. If false, you should print the first page first. This is relevant only if you are trying to print a multipage document. public abstract void end () The end() method terminates the print job. This is the last method you should call when printing; it does any cleaning up that s necessar y. public void finalize () The finalize() method is called by the garbage collector. In the event you forget to call end(), finalize() calls it for you. However, it is best to call end() as soon as you know you have finished printing; don t rely on finalize(). 17.3 Component Methods The methods that start the printing process come from either the Component or Container class and are inherited by all their children. All components inherit the printall() and print() methods. Containers also inherit the printcomponents() method, in addition to printall() and print(). A container should call print- Components() to print itself if it contains any components. Otherwise, it is sufficient to call printall(). These methods end up calling paint(), which does the actual drawing.

518 CHAPTER 17: PRINTING 17.4 Printing Example Now that you know about the different classes necessary to print, let s put it all together. Printing takes four steps: 1. Get the PrintJob: PrintJob pjob = gettoolkit().getprintjob(this, "Job Title", (Properties)null); 2. Get the graphics context from the PrintJob: Graphics pg = pjob.getgraphics(); 3. Print by calling printall() or print(). When this method returns, you can call dispose() to send the page to the printer: printall(pg); pg.dispose(); // This is like sending a form feed 4. Clean up after yourself: pjob.end(); The following code summarizes how to print: // Java 1.1 only PrintJob pjob = gettoolkit().getprintjob(this, "Print?", (Properties)null); if (pjob!= null) { Graphics pg = pjob.getgraphics(); if (pg!= null) { printall(pg); pg.dispose(); pjob.end(); This code prints the current component: what you get from the printer should be a reasonable rendition of what you see on the screen. Note that we didn t need to modify paint() at all. That should always be the case if you want your printer output to look like your onscreen component. 17.5 Printing Arbitrary Content Of course, in many situations, you want to do more than print the appearance of a component. You often want to print the contents of some component, rather than the component itself. For example, you may want to print the text the user has typed into a text area, rather than the text area itself. Or you may want to print the contents of a spreadsheet, rather than the collection of components that compose the spreadsheet.

17.5 PRINTING ARBITRAR Y CONTENT 519 Java 1.1 lets you print arbitrary content, which may include multipage documents. You aren t restricted to printing your components appearance. In many ways, the steps required to print arbitrary content are similar to those we outlined previously. However, a few tricks are involved: 1. Get the PrintJob: PrintJob pjob = gettoolkit().getprintjob(this, "Job Title", (Properties)null); 2. Get the graphics context from the PrintJob: Graphics pg = pjob.getgraphics(); 3. Don t call printall() or print(). These methods will try to draw your component on the page, which you don t want. Instead, get the dimensions of the page by calling getpagedimension(): pjob.getpagedimension(); 4. Set the font for your graphics context; then get the font metrics from your graphics context. Font times = new Font ("SansSerif", Font.PLAIN, 12); pg.setfont(times); FontMetrics tm = pg.getfontmetrics(times); 5. Draw whatever you want into the graphics context, using the methods of the Graphics class. If you are drawing text, it s your responsibility to do all the positioning, making sure that your text falls within the page boundaries. By the time you re through with this, you ll have the FontMetrics class memorized. 6. When you ve finished drawing the current page, call dispose(); this sends the page to the printer and releases the resources tied up by the PrintGraphics object. pg.dispose(); // This is like sending a form feed 7. If you want to print more pages, return to step 2. 8. Clean up after yourself: pjob.end(); Remember to set a font for the PrintGraphics object explicitly! It doesn t have a default font. An example that loads and prints a text file is available from this book s Web page.