Unfortunately, there is not much that can be done automatically when you print. Instead, we have to go through a lot of mechanical, non-OO (object-oriented) steps to finish printing. But when printing a graphical component, it may be somewhat automated: By default, the print () method calls Paint () to do its job. Most of the time this is enough, but if you want to do something special, you have to know the geometry of the page.
The following example illustrates the printing of text and graphics, as well as the different methods that can be taken when printing graphics. In addition, it tests print Support:
: Printdemo.java//Printing with Java 1.1 import java.awt.*;
Import java.awt.event.*; public class Printdemo extends Frame {button Printtext = New button ("Print Text"), PrintGraphics = New button (
"Print Graphics");
TextField ringnum = new TextField (3);
Choice faces = new Choice ();
Graphics g = null; Plot Plot = new Plot3 ();
Try different plots Toolkit tk = Toolkit.getdefaulttoolkit ();
Public Printdemo () {Ringnum.settext ("3");
Ringnum.addtextlistener (New Ringl ());
panel p = new Panel ();
P.setlayout (New FlowLayout ());
Printtext.addactionlistener (New TBL ());
P.add (Printtext);
P.add (New Label ("Font:"));
P.add (faces);
Printgraphics.addactionlistener (New GBL ());
P.add (PrintGraphics);
P.add (New Label ("Rings:"));
P.add (Ringnum);
SetLayout (New BorderLayout ());
Add (P, Borderlayout.north);
Add (plot, borderlayout.center);
string[] fontlist = Tk.getfontlist (); for (int i = 0; i < fontlist.length;i++) Faces.add (Fontlist[i]);
Faces.select ("Serif");
Class Printdata {public PrintJob pj;
public int pagewidth, pageheight;
Printdata (String jobName) {PJ = Gettoolkit (). Getprintjob (printdemo.this, jobName, NULL);
if (PJ!= null) {pagewidth = Pj.getpagedimension (). width;
Pageheight= pj.getpagedimension (). Height;
g = Pj.getgraphics ();
} void End () {pj.end ();}
Class Changefont {private int stringheight;
Changefont (String face, int style,int point) {if (G-!= null) {G.setfont (new Font (face, style, point));
Stringheight = G.getfontmetrics (). GetHeight ();
} int Stringwidth (String s) {return g.getfontmetrics (). Stringwidth (s);
int Stringheight () {return stringheight;} Class TBL implements ActionListener {public void actionperformed (ActionEvent e) {printdata PD = n
EW Printdata ("Print Text Test"); Null means print job canceled:if (PD = null) return;
String s = "Printdemo";
Changefont CF = new Changefont (Faces.getselecteditem (), font.italic,72);
g.DrawString (S, (Pd.pagewidth-cf.stringwidth (s))/2, (Pd.pageheight-cf.stringheight ())/3);
s = "A smaller point size";
CF = new Changefont (Faces.getselecteditem (), Font.Bold, 48); g.DrawString (S, (Pd.pagewidth-cf.stringwidth (s))/2, (int) (Pd.pageheight-cf.stringheigh
T ())/1.5));
G.dispose ();
Pd.end ();
Class GBL implements ActionListener {public void actionperformed (ActionEvent e) {printdata PD =
New Printdata ("Print Graphics Test");
if (PD = null) return;
Plot.print (g);
G.dispose ();
Pd.end ();
Class Ringl implements TextListener {public void textvaluechanged (TextEvent e) {int i = 1; try {i = Integer.parseint(Ringnum.gettext ());
catch (NumberFormatException ex) {i = 1;
} plot.rings = i;
Plot.repaint ();
} public static void Main (string[] args) {Frame Pdemo = new Printdemo ();
Pdemo.settitle ("Print Demo"); Pdemo.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {SYSTEM.E
XIT (0);
}
});
Pdemo.setsize (500, 500);
Pdemo.setvisible (TRUE);
} class Plot extends Canvas {public int rings = 3;} Class Plot1 extends Plot {//Default print () calls paint (): public void Paint (Graphics g) {int w = getsize (). wid
Th
int h = getsize (). Height;
int XC = W/2;
int YC = W/2;
int x = 0, y = 0;
for (int i = 0; i < rings i++) {if (x < xc && y < YC) {g.drawoval (x, Y, W, h); x + 10;
Y + 10; W-= 20;
H-= 20; Class Plot2 extends Plot {//To fit the "page", youMust//know whether you ' re printing or painting:public void paint (Graphics g) {int W, h;
if (g instanceof printgraphics) {PrintJob PJ = ((PrintGraphics) g). Getprintjob ();
W = pj.getpagedimension (). width;
h = pj.getpagedimension (). Height;
else {w = GetSize (). width;
h = getsize (). Height;
int XC = W/2;
int YC = W/2;
int x = 0, y = 0;
for (int i = 0; i < rings i++) {if (x < xc && y < YC) {g.drawoval (x, Y, W, h); x + 10;
Y + 10; W-= 20;
H-= 20; Class Plot3 extends Plot {//somewhat better. Separate//printing from painting:public void print (Graphics g) {//Assume it ' s a printgraphics OBJECT:PR
Intjob PJ = ((PrintGraphics) g). Getprintjob ();
int w = pj.getpagedimension (). width;
int h = pj.getpagedimension (). Height;
Dographics (G, W, h); public void Paint (Graphics g) {int w = getsize (). width;
int h = getsize (). Height;
Dographics (G, W, h);
} private void Dographics (Graphics g, int w, int h) {int xc = W/2;
int YC = W/2;
int x = 0, y = 0;
for (int i = 0; i < rings i++) {if (x < xc && y < YC) {g.drawoval (x, Y, W, h); x + 10;
Y + 10; W-= 20;
H-= 20; }
}
}
} ///:~
This program allows us to select fonts from a select list box (and we notice that many useful fonts have been strictly restricted in Java version 1.1, and we don't have any good fonts available to install on our machines). It uses these fonts to play bold, italic, and different sizes of text. In addition, a new component called the drawing was created to illustrate the graphic. When you print a graphic, the ring that the drawing owns will be displayed on the screen and printed on paper, and the three derivative classes plot1,plot2,plot3 the task in a different way so that we can see the things we choose. Also, we can change some ring--in a drawing. This is interesting because it demonstrates the fragility of printing in Java version 1.1. In my system, when the ring count shows "too high" (what exactly does that mean?) , the printer gives an error message and does not work correctly, and the printer works well when the count gives "low enough" information. We will also note that the size of the page is generated when you print to a paper that does not appear to match the actual size. These features may be loaded into future releases of Java, and we can use this program to test it.
This program facilitates reuse and can encapsulate functionality to internal classes whenever it is used. For example, whenever I want to start a print job (regardless of graphics or text), I have to create a PrintJob print work object that has its own graphics object, along with the width and height of the page. The PrintJob print work object and the extracted page size are encapsulated together into the Printdata class print class.
1. Print text
The concept of printed text is straightforward: we choose a font and size, determine where the string is located on the page, and use the Graphics.drawsrting () method to draw a string on the page. This means that, in any case, we must accurately calculate where each line of string exists on the page and make sure that the string does not go beyond the bottom of the page or conflict with other rows. If we want to do word processing, we will work well with us. Changefont encapsulates a small amount of change from one font to another and automatically creates a new Font object and the font that we want, styles (bold and italic-not currently supported by underscores, hollows, etc.) and dot-matrix size. It also simply computes the width and height of the string. When we press the "Print text" button, the TBL receiver is activated. We can note that it prints out the string in the computed position by repeatedly creating the Changefont object and calling drawstring (). Note whether these calculations produce the expected results. (The version I'm using is not wrong.) )
2. Print Graphics
The GBL receiver is activated when the Print graphics button is pressed. We need to print, create the Printdata object initialized, and then we simply call the print () printing method for this component. To force printing, we must call the Dispose () method for the drawing object and call End () ending method for the Printdata object (or change to call End () for PrintJob. )
This work continues in the drawing object. We can see that the base class drawing is simple-it expands the canvas and includes an interrupt call ring to indicate how many central ring needs to be painted on this particular canvas. These three derivative classes show different ways to achieve one goal: on the screen and on the printed page.
PLOT1 uses the simplest programming approach: ignoring the differences between painting and printing, and overloading the paint () painting method. This working method is used because the default print () printing method simply changes the working method to invoke paint () instead. However, we notice that the size of the output depends on the size of the canvas on the screen, because the width and height are determined when the Canvas.getsize () method is invoked, so this is reasonable. If the size of our image is fixed, the rest of the picture will be acceptable. When the size of the painted look is so important, we have to delve into the importance of size. Unfortunately, as we will see in Plot2, this approach becomes tricky. Because of some good reasons we don't know, we can't simply ask the drawing object to draw its own size and appearance. This will make the entire processing work very good. Instead, if we print instead of painting, we have to test the printgrapics using the RTTI instanceof keyword (described in the book in Chapter 11), and then retrace the shapes and invoke the unique PrintGraphics method: Getprintjob () Method. Now we have the printjob handle and we can find the height and width of the paper. This is a hacky method, but maybe it's a reasonable reason for it. (In other ways, we now see some other library designs, so we might get the idea of the designers.) )
We can note that the paint () painting method in Plot2 examines the possibility of printing and drawing. But because the print () method will be invoked when it is printed, why not use that method? This method is also used in Plot3, and it eliminates the need for instanceof use, because in the print () method we can assume that we can sculpt a PrintGraphics object. It's not bad. This situation is improved by placing the public painting code into a separate Dographics () method.
2. Running frames within the program slice
What if we want to print in a piece of the program? Well, in order to print anything, we have to have a PrintJob object with the Getprintjob () method of the tool Component object, set a unique frame object instead of a program piece object. It seems likely that it will print from an application rather than from a single piece of the program. However, it turns out that we can create a frame from one piece of the program (instead, as I've done in the program or application example so far, I can generate a patch and frame it.) )。 This is a very useful technique because it allows us to use some applications in the program (as long as they do not interfere with the safety of the program piece). However, when the application window appears in the patch, we notice that the Web browser inserts a few warnings on it, some of which produce the words "warning:applet window. (Warning: Patch Windows)".
We will see that this technique is very straightforward to put a frame into the program. The only thing is that when the user closes it we have to add the frame code (instead of calling System.exit ()):
: Printdemoapplet.java
//Creating a Frame from within a Applet
import java.applet.*;
Import java.awt.*;
Import java.awt.event.*;
public class Printdemoapplet extends applets {public
void init () {
button b = New button ("Run Printdemo");
B.addactionlistener (New PDL ());
Add (b);
}
Class PDL implements ActionListener {public
void actionperformed (ActionEvent e) {
final printdemo pd = new Prin Tdemo ();
Pd.addwindowlistener (New Windowadapter () {public
void windowclosing (WindowEvent e) {
pd.dispose ();
}
});
Pd.setsize (+);
Pd.show ();}}
///:~
With the Java 1.1 version of the printing support feature is some confusion. Some propaganda seems to state that we can print in one piece of the program. But the Java security system contains a feature that stops a piece of the program that is initializing the print job, and that the initialization of the program is done through a Web browser or a program browser. In writing this book, it looks as if it leaves an undecided controversy. When I run this program in a Web browser, the Printdemo (Print sample) window just appears, but it can't print from the browser at all.