Copy codeThe Code is as follows:
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;
/**
* Uses the original paging method to render JTextArea and provides a print preview mechanism.
* <P>
* In fact, we can 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 be 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 mechanic </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 <= 50; 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. setdefaclocloseoperation (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"); // the task list appears in the system.
Job. setPrintable (this );
}
@ Override
Public int print (Graphics graphics, PageFormat pageFormat, int pageIndex)
Throws PrinterException {
/*
* It is safe to use a copy of this graphics as this will 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 that is on 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 that this page is part of the printed document */
Return PAGE_EXISTS;
}
@ Override
Public void actionreceivmed (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
. Setdefaclocloseoperation (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 marg.pdf = 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 * margsion, h + 2 * marginY );
}
@ Override
Public void paint (Graphics g ){
Graphics2D g2 = (Graphics2D) g. create ();
G2.translate (marg.pdf, 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 ();
}
}
}
}
}