Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Printing on Muliple Pages

Status
Not open for further replies.

brinker

Programmer
May 31, 2001
48
CA
help!!!

I have spent the last few days trying to print a JTextArea over multiple pages. The code I have worked with seems to print the contents of a JTextArea fine over a single page, but fails to print any further. I have provided this code below. If anybody knows how I can extend it to print over muliple pages (providing there is enough data), please let me know.

import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;
/**
* A small program to show how to print the contents of a
* JTextArea.
*/
public class Print extends JFrame implements ActionListener, Printable{
JTextArea textArea;
JScrollPane areaScrollPane;
Book book;
/**
* Constructor. Set up the GUI.
*/
public Print( ){
pack( );
addWindowListener( new CloseWindow( ));
String string = "Line one.\nLine two.\nLine three.";
textArea = new JTextArea( string);
areaScrollPane=new JScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(250,250));
getContentPane().add( areaScrollPane, BorderLayout.CENTER);
JButton button = new JButton( "Print");
button.addActionListener( this);
getContentPane().add( button, BorderLayout.SOUTH);
setSize(300,300);
show( );
}
/**
* Called when the user clicks on the print button.
*/
public void actionPerformed( ActionEvent e){

book= new Book();
book.append(new Print(), new PageFormat());

PrinterJob printJob = PrinterJob.getPrinterJob( );
printJob.setPrintable( this);
printJob.setPageable(book);

if (printJob.printDialog()) {
try {
printJob.print( );
}
catch( Exception PrintException){ }
}
}
/**
* This method does the actual work - the printing.
* It uses JTextAreas printAll(Graphics) method. If
* n is "greater or equal to 1" then the requested
* page does not exist. n must be 0 for the page to be
* printed.
* @param g - the context into which the page is
* drawn.
* @param f - the size and orientation of the page
* being drawn.
* @param n - the zero based index of the page to be
* drawn.
*/
public int print( Graphics g, PageFormat f, int n) throws PrinterException{
if( n >= 1) {
return Printable.NO_SUCH_PAGE;
}
g.translate( 100, 100);
textArea.printAll( g);
return Printable.PAGE_EXISTS;
}
/**
* The main method.
*/
public static void main( String s[]){
new Print( );
}
}
/**
* Allow this frame to close.
*/
class CloseWindow extends WindowAdapter{
public void windowClosing( WindowEvent e){
System.exit( 0);
}
}



thanks

Brinker
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top