Java Reference
In-Depth Information
}
catch
(PrinterException pex) {
pex.printStackTrace();
}
}
■
19.3
An example application
The two classes listed below form an application that allows a panel to be printed.
Class
PrintPanel
is specified in Figure 19.1. To make
PrintPanel
printable, we
have to implement interface
Printable
by defining the
print
method as described
in Section 19.1.
File:
its/Printing/PrintPanel.java
1.
package
its.Printing;
2.
3.
import
java.awt.Color;
import
java.awt.Dimension;
4.
import
java.awt.Graphics;
5.
import
java.awt.print.PageFormat;
6.
import
java.awt.print.Printable;
7.
import
javax.swing.JPanel;
8.
import
javax.swing.RepaintManager;
9.
10.
11.
public class
PrintPanel
extends
JPanel
implements
Printable
{
12.
13.
public
PrintPanel() {
14.
this
.setBackground(Color.white);
15.
this
.setPreferredSize(
new
Dimension(300, 200));
16.
}
17.
18.
public void
paintComponent(Graphics g) {
19.
super
.paintComponent(g);
20.
g.setColor(Color.black);
21.
g.drawRect(20,20,100,50);
22.
g.fillOval(80,80,60,30);
23.
g.drawString("Printing in JAVA is easy!",100,150);
24.
g.setColor(Color.red);
25.
g.drawRect(0,0,299,199);
}
26.
27.
28.
public int
print(Graphics g, PageFormat pageFormat,
int
pageIndex) {
if
(pageIndex > 0) {
29.
return
(NO_SUCH_PAGE);
30.
}
else
{
31.
int
x=(
int
)pageFormat.getImageableX() + 1;
32.
Search WWH ::
Custom Search