import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class PrintExample extends JFrame implements ActionListener { final int ROWS = 30; final int COLUMNS = 40; private JButton printButton; private JTextArea textArea; private JScrollPane scrollPane; public static void main ( String args[]) { PrintExample printExample = new PrintExample(); WindowAdapter windowAdapter = new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } }; printExample.addWindowListener( windowAdapter ); } public PrintExample() { Container container = getContentPane(); container.setLayout( new FlowLayout() ); printButton = new JButton( "Print" ); textArea = new JTextArea(ROWS,COLUMNS); Insets i = new Insets(25, 25,25, 25); scrollPane = new JScrollPane(textArea); container.add(printButton); container.add(scrollPane); printButton.addActionListener(this); textArea.setMargin(i); setSize( 600, 600 ); show(); } public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { PrintJob printJob = getToolkit().getPrintJob(this,"Printing Test", null, null); if (printJob != null) { Graphics graphics = printJob.getGraphics(); printLongString(printJob,graphics ,textArea.getText()); graphics.dispose(); // flush page printJob.end(); } } } // Print string to graphics via printjob // Does not deal with word wrap or tabs void printLongString (PrintJob printJob, Graphics graphics, String s) { final int PAGE_TOP = 25; final int PAGE_BOTTOM = 50; final int PAGE_LEFT = 25; final int TAB_WIDTH = 50; StringReader stringReader = new StringReader (s); LineNumberReader lineNumberReader = new LineNumberReader (stringReader); String nextLine; int pageHeight = printJob.getPageDimension().height; Font font = new Font("Helvetica", Font.PLAIN, 12); graphics.setFont (font); FontMetrics fontMetrics = graphics.getFontMetrics(font); int fontHeight = fontMetrics.getHeight(); int fontDescent = fontMetrics.getDescent(); int curHeight = PAGE_TOP; try { do { nextLine = lineNumberReader.readLine(); if (nextLine != null) { if ((curHeight + fontHeight) > pageHeight - PAGE_BOTTOM) { // New Page graphics.dispose(); graphics = printJob.getGraphics(); if (graphics != null) { graphics.setFont (font); } curHeight = PAGE_TOP; } curHeight += fontHeight; if (graphics != null) { int Tabs; Tabs = 0; while( Tabs < nextLine.length() && nextLine.charAt(Tabs) == '\t') Tabs++; //remove the leading tabs graphics.drawString (nextLine, PAGE_LEFT + (Tabs * TAB_WIDTH), curHeight - fontDescent); } else { System.out.println ("graphics null"); } } } while (nextLine != null); } catch (Throwable t) { t.printStackTrace(); } } }