The printing interface can be improved by adding the Pageable interface, which tells the system how many pages there are in the document. The example below prints a page.
package myStuff;
import java.awt.*;
import java.awt.print.*;
public class PrintTest
{
public static void main(String[] argv) throws Exception
{
// instructions for what to print on each page
final Printable pr = new Printable()
{
public int print(Graphics g, PageFormat fmt, int page)
{
if (page != 0) // print page #0 only
return NO_SUCH_PAGE;
g.setColor(Color.blue);
g.drawOval(100, 100, 200, 200);
g.drawString("Hello, Printer", 150, 200);
return PAGE_EXISTS;
}
};
// specifies how many pages that there are
final Pageable pa = new Pageable()
{
public int getNumberOfPages(){return 1;} // a one-page document
public PageFormat getPageFormat(int pageIndex)
throws IndexOutOfBoundsException
{return PrinterJob.getPrinterJob().defaultPage();}
public Printable getPrintable(final int pi)
throws IndexOutOfBoundsException{return pr;}
};
// show printer dialog and print if not cancelled
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(pr); // tells what to print
pj.setPageable(pa); // tells #of pages
if (pj.printDialog())
pj.print();
System.exit(0);
}
}