Import Java.awt.BasicStroke;
Import Java.awt.BorderLayout;
Import Java.awt.Color;
Import java.awt.Component;
Import java.awt.Dimension;
Import Java.awt.Font;
Import Java.awt.FontMetrics;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.GridLayout;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.awt.event.MouseAdapter;
Import java.awt.event.MouseEvent;
Import Java.awt.print.PageFormat;
Import java.awt.print.Printable;
Import java.awt.print.PrinterException;
Import Java.awt.print.PrinterJob;
Import Javax.swing.JButton;
Import Javax.swing.JDialog;
Import Javax.swing.JFrame;
Import Javax.swing.JPanel;
Import Javax.swing.JScrollPane;
Import Javax.swing.JTextArea;
Import javax.swing.SwingUtilities;
Import javax.swing.WindowConstants;
Import javax.swing.text.BadLocationException;
Import javax.swing.text.Document;
/**
* The original paging method was used to render the JTextArea, providing a print preview mechanism.
* <p>
* In fact, we can also print JTextArea in other ways:
* <ol>
* <li>{@code Component.print (Graphics g);} or
* {@code component.printall (Graphics g);} </li>
* <li>{@code Component.paint (Graphics g);} or
* {@code component.paintall (Graphics g);} Whose rending may slightly
* Different to the "previous method" (for example, <code>JFrame</code>) </li>
* <li>{@code Jtable.print ();} or {@code jtextcomponent.print ();} provide
* Especially powerful and convenient printing mechanism</li>
* </ol>
*
* @author Gaowen
*/
public class Printuicomponent extends JPanel implements ActionListener,
printable {
Private static final long serialversionuid = 4797002827940419724L;
private static JFrame frame;
Private JTextArea Textareatoprint;
Private PrinterJob job;
Private int[] pagebreaks;//array of page break line positions
Private string[] Textlines;
Private header header;
Public Printuicomponent () {
Super (New BorderLayout ());
Textareatoprint = new JTextArea (50, 20);
for (int i = 1; I <= i++) {
Textareatoprint.append ("line" + i + "\ n");
}
JScrollPane ScrollPane = new JScrollPane (textareatoprint);
Scrollpane.setpreferredsize (New Dimension (250, 200));
Add (ScrollPane, borderlayout.center);
JButton Printbutton = new JButton ("Print this TextArea");
Printbutton.setname ("Printbutton");
Printbutton.addactionlistener (this);
JButton Printpreviewbutton = new JButton ("Print Preview");
Printpreviewbutton.setname ("Printpreviewbutton");
Printpreviewbutton.addactionlistener (this);
JPanel Buttongroup = new JPanel (New GridLayout (2, 1));
Buttongroup.add (Printbutton);
Buttongroup.add (Printpreviewbutton);
Add (Buttongroup, Borderlayout.south);
/* Initialize printerjob * *
Initprinterjob ();
}
public static void Main (string[] args) {
Swingutilities.invokelater (New Runnable () {
@Override
public void Run () {
Createandshowgui ();
}
});
}
private static void Createandshowgui () {
frame = new JFrame ("Print UI Example");
Frame.setcontentpane (New Printuicomponent ());
Frame.pack ();
Frame.setlocationrelativeto (NULL);
Frame.setdefaultcloseoperation (Windowconstants.exit_on_close);
Frame.setvisible (TRUE);
}
private void Inittextlines () {
Document doc = Textareatoprint.getdocument ();
try {
String Text = Doc.gettext (0, Doc.getlength ());
Textlines = Text.split ("\ n");
catch (Badlocationexception e) {
E.printstacktrace ();
}
}
private void Initprinterjob () {
Job = Printerjob.getprinterjob ();
Job.setjobname ("Print TextArea");//appears in System print task List
Job.setprintable (this);
}
@Override
public int print (Graphics Graphics, Pageformat pageformat, int pageIndex)
Throws PrinterException {
/*
* It is safe to use a copy of the This graphics as this would not involve
* Changes to it.
*/
graphics2d g2 = (graphics2d) graphics.create ();
* * Calculate "pagebreaks" * *
Font font = new Font ("Serif", Font.plain, 12);
FontMetrics metrics = g2.getfontmetrics (font);
int lineheight = Metrics.getheight ();
if (PageBreaks = = null) {
Inittextlines ();
int linesperpage = (int) (Pageformat.getimageableheight ()/lineheight);
int numbreaks = (textlines.length-1)/linesperpage;
PageBreaks = new Int[numbreaks];
for (int b = 0; b < numbreaks; b++) {
PAGEBREAKS[B] = (b + 1) * linesperpage;
}
}
/* Condition to exit Printing * *
if (PageIndex > Pagebreaks.length) {
return no_such_page;
}
/* (0,0) is outside the imageable area, translate to avoid clipping * *
G2.translate (Pageformat.getimageablex (), Pageformat.getimageabley ());
/* Draw each line, this page */
int y = 0;
int start = (PageIndex = 0)? 0:PAGEBREAKS[PAGEINDEX-1];
int end = (PageIndex = = pagebreaks.length)? Textlines.length
: Pagebreaks[pageindex];
for (int line = start; line < end; line++) {
Y + + lineheight;
G2.drawstring (Textlines[line], 0, y);
}
* Dispose of the graphics copy * *
G2.dispose ();
* Tell the caller, this page is part of the printed document */
return page_exists;
}
@Override
public void actionperformed (ActionEvent e) {
Object Actioneventsource = E.getsource ();
if (Actioneventsource instanceof JButton) {
JButton button = (JButton) Actioneventsource;
if (Button.getname (). Equals ("Printbutton")) {
PageBreaks = null;//Reset Pagination
Boolean OK = Job.printdialog ();
if (OK) {
try {
Job.print ();
catch (PrinterException ex) {
/* The job did not successfully complete * *
Ex.printstacktrace ();
}
}
else if (Button.getname (). Equals ("Printpreviewbutton")) {
PageBreaks = null;//Reset Pagination
Createandshowpreviewdialog ();
}
}
}
private void Createandshowpreviewdialog () {
jdialog previewdialog = new JDialog (frame, "Print Preview Dialog ", true);
jpanel ContentPane = new JPanel (new BorderLayout ());
previewarea Previewarea = new Previewarea ();
previewarea.addmouselistener (New Previewareamouseadapter (Previewarea));
jscrollpane ScrollPane = new JScrollPane (Previewarea);
contentpane.add (ScrollPane, Borderlayout.center);
header = new Header (Previewarea);
contentpane.add (header, Borderlayout.north);
previewdialog.setcontentpane (ContentPane);
previewdialog.setsize (600, 600);
previewdialog
.setdefaultcloseoperation (windowconstants.dispose_on_ Close);
previewdialog.setvisible (TRUE);
}
Private class Header extends Component {
Private static final long serialversionuid = -1741188309769027249l;
Private Previewarea Previewarea;
Private Boolean paintable;
Private Header (Previewarea Previewarea) {
This.previewarea = Previewarea;
}
private void Setpaintable (Boolean paintable) {
this.paintable = paintable;
}
@Override
public void Paint (Graphics g) {
if (paintable) {
G.setcolor (Color.gray);
g.DrawString (
String.valueof (Previewarea.getpageindex () + 1)
+ "/"
+ string.valueof (pagebreaks.length + 1)
+ "Pages" (Click left mouse button to preview next page; Right to previous) ",
10, 15);
}
}
@Override
Public Dimension getPreferredSize () {
return new Dimension (Super.getpreferredsize (). width, 20);
}
}
Private class Previewarea extends Component {
Private static final long serialversionuid = -6384174997251439843l;
Private Pageformat Pageformat;
private int pageIndex;
private int w;
private int h;
Private final int marginx = 10;
Private final int marginy = 20;
Private Previewarea () {
Pageformat = Job.pagedialog (Job.defaultpage ());
PageIndex = 0;
w = (int) pageformat.getwidth ();
h = (int) pageformat.getheight ();
}
private int Getpageindex () {
return pageIndex;
}
private void Setpageindex (int pageIndex) {
This.pageindex = PageIndex;
}
@Override
Public Dimension getPreferredSize () {
return new Dimension (W + 2 * marginx, H + 2 * marginy);
}
@Override
public void Paint (Graphics g) {
graphics2d g2 = (graphics2d) g.create ();
G2.translate (Marginx, Marginy);
G2.drawrect (0, 0, W, h);
int IX = (int) (Pageformat.getimageablex ()-1);
int iy = (int) (Pageformat.getimageabley ()-1);
int IW = (int) (Pageformat.getimageablewidth () + 1);
int ih = (int) (Pageformat.getimageableheight () + 1);
G2.setstroke (New Basicstroke (1f, Basicstroke.cap_round,
Basicstroke.join_round, 10f, new float[] {5, 5}, 0f));
G2.drawrect (ix, IY, IW, IH);
try {
PrintUIComponent.this.print (G2, Pageformat, PageIndex);
catch (PrinterException e) {
E.printstacktrace ();
}
G2.dispose ();
Header.setpaintable (TRUE);
Header.repaint ();
}
}
Private class Previewareamouseadapter extends Mouseadapter {
Private Previewarea Previewarea;
Private Previewareamouseadapter (Previewarea Previewarea) {
This.previewarea = Previewarea;
}
@Override
public void mouseclicked (MouseEvent e) {
int currentindex = Previewarea.getpageindex ();
if (E.getbutton () = = Mouseevent.button1) {
/* Next Page * *
if (Currentindex < pagebreaks.length) {
Previewarea.setpageindex (Currentindex + 1);
Previewarea.repaint ();
}
else if (e.getbutton () = = Mouseevent.button3) {
/* Previous Page * *
if (Currentindex > 0) {
Previewarea.setpageindex (currentIndex-1);
Previewarea.repaint ();
}
}
}
}
}