salva il seguente codice in un file Print.java
mport 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;
JTextPane myEditor;
/**
* Constructor. Set up the GUI.
*/
public Print( JTextPane editor){
myEditor=editor;
pack( );
setSize( new Dimension(300,300));
addWindowListener( new CloseWindow( ));
String text = myEditor.getText();
textArea = new JTextArea( text);
getContentPane().add( textArea, BorderLayout.CENTER);
JButton button = new JButton( "Print");
button.addActionListener( this);
getContentPane().add( button, BorderLayout.SOUTH);
show( );
}
/**
* Called when the user clicks on the print button.
*/
public void actionPerformed( ActionEvent e){
PrinterJob printJob = PrinterJob.getPrinterJob( );
printJob.setPrintable( this);
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) {
System.out.print( "I am in here");
return Printable.NO_SUCH_PAGE;
}
System.out.println( "now I am in here");
g.translate( 100, 100);
textArea.printAll( g);
return Printable.PAGE_EXISTS;
}
/**
* The main method.
*/
public static void main( String s[]){
//new Print( myEditor);
}
}
/**
* Allow this frame to close.
*/
class CloseWindow extends WindowAdapter{
public void windowClosing( WindowEvent e){
//System.exit( 0);
}
}

Rispondi quotando