Thursday, November 6, 2008

Program how to print out a line of text in Java



import java.awt.*;
import java.awt.geom.*;
import java.awt.print.*;
/**
Simple printing application that
will demonstrate how to print out simple text
*/

class MyPage implements Printable
{
public void paint (Graphics g) // This method will define what will
{ // be printed on paper
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(new Font("Arial", Font.BOLD, 30));
g2d.drawString ("Hello World of Paper!", 200, 150);

}
public int print (Graphics g, PageFormat f, int i)
{
if (i != 0) // To prevent overflow. i indicates number of pages to print
return NO_SUCH_PAGE;
paint (g); // Call paint method
return PAGE_EXISTS;
}
}
class MyPrinter
{
public static void main (String[] args)
{
PrinterJob job = PrinterJob.getPrinterJob();
System.out.println ("Staring printer...");
job.setPrintable(new MyPage());
if (job.printDialog()) // Show the printing dialog
{
try {
job.print(); // Attempt printing
}
catch (PrinterException e)
{
e.printStackTrace();
}
}
}
}

No comments: