Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 136,140 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,064 people online right now. Registration is fast and FREE... Join Now!




java printing

 
Reply to this topicStart new topic

> java printing, print Hello World

alpha02
Group Icon



post 3 Jun, 2007 - 05:33 PM
Post #1


Introduction

Printing in Java is a pretty complex thing, and I will try to introduce you to the basics by creating a small application that will print Hello World on a blank page. After this tutorial, you will be able to print a lot of things if you master the basics. You must have the basics of Java as well as GUI notions to be able to follow. Let's get started.

Things you should know before starting

To be able to follow, you should know the following:

-Basics of Java langage
-GUI creation
-Package importing
-Class implementing

You master all that? Then let's go.

Creating the GUI

I am not going to give you a tutorial about GUI creation, we will simply create a GUI with a button to print Hello World:

CODE
//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
    //Static swing components
    static JFrame frmMain;
    static Container pane;
    static JButton btnPrint;

    public static void main (String[] args){
        //Apply system look and feel
        try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
              catch (Exception e){}
        
        //Create and resize frame
        frmMain = new JFrame ("Sample printing application");
        frmMain.setSize(300, 200); //300x200 pixels
        pane = frmMain.getContentPane();
        pane.setLayout(null); //Use null layout

        //Create components
        btnPrint = new JButton ("Print"); //Create our button

        //Add components to pane
        pane.add(btnPrint);

        //Set components' bounds
        btnPrint.setBounds(5, 5, 100, 25); //Arguments: x, y, width, height

        //Make frame visible
        frmMain.setVisible(true);
    }
}


This is it for the GUI creation. If you run the program, all you will see will be a window with a button in it that does absolutely nothing when clicked. Let's make it do something (hopefully printing)!

Adding the button's action

If your ActionListener stuff is a little rusty, I'll refresh it for you: we will add the button's action by using:

CODE
btnPrint.addActionListener(new btnPrintAction());


In this example, btnPrintAction must be an ActionListener. We will achieve this by implementing ActionListener to the btnPrintAction class we will create:

CODE
public static class btnPrintAction implements ActionListener{

}


Now, if you create this class in your main class, you will get an error message similar to:
The class btnPrintAction must implement the abstract method ActionListener.actionPerformed (ActionEvent)

The message says it all, let's implement this method:

CODE
public static class btnPrintAction implements ActionListener{
    public void actionPerformed (ActionEvent e){
        //Actions happen here when you click the button!
    }
}


The actionPerformed method is called when you click the button. Make sure you understand this before you proceed, even if it is not the main purpose of this tutorial.

Implementing the Printable interface

To be able to get something out of your printer, you need a class which implements the Printable interface. Remember: a class can only extend one class, but can implement multiple ones! What I mean: implement both ActionListener and Printable to the class you just created, and import java.awt.print.*.

CODE
public static class btnPrintAction implements ActionListener, Printable{ //Implement both ActionListener and Printable
    public void actionPerformed (ActionEvent e){
        //Actions happen here when you click the button!
    }
}


Another error will occur this time: we need a print method. Let's add it now:

CODE
public static class btnPrintAction implements ActionListener, Printable{
    public int print(Graphics gx, PageFormat pf, int page) throws PrinterException {
        return NO_SUCH_PAGE;
    }
    public void actionPerformed(ActionEvent e) {
        //Do something
    }
}


At first glance, the print method used here may seem complicated with its arguments. Don't worry, they are not all used and are quite simple:

Graphics gx: A graphics object in which we wil add the different element to make a nice page to print. We can add text, images, and everything we want out of our printer.
PageFormat pf: The page format, specified by the Print dialog we will pop later.
int page: The number of the page we are printing. The first page has the index 0.

Feel free to explore the methods of the objects specified above. This is it, our class is created. Now let's add some real action!

Popping the print dialog

When you click the button, a print dialog should pop. Trust me, you absolutely need this one. Put that in the actionPerformed method:

CODE
PrinterJob job = PrinterJob.getPrinterJob(); //Get the printer's job list
job.setPrintable(this); //We print with this class (btnPrintAction, which implements Printable)
if (job.printDialog() == true) { //If we clicked OK in the print dialog
    try {job.print();} catch (PrinterException ex){
        //It did not work (PrinterException thrown), so add any error handling routines.
    }
}


Now, this code will pop a dialog (the one that you always see when you attempt to print a document) asking for many parameters, and will print when you click OK. We are now ready to actually configure what will be printed.

Setting the page layout

Although the title may seem to introduce a complex part, don't get fooled. We will only tell the printer to print "Hello World" on the page (5 lines needed). This is in the print method. One important thing: the units used are not pixels! They are points, and there are 72 points in an inch.

CODE
if (page>0){return NO_SUCH_PAGE;}


Since we need only one page, if we attempt to print a second page (remember page indexes start at zero), this will prevent multiple page printing.

CODE
Graphics2D g = (Graphics2D)gx;


This casts the Graphics object gx to a Graphics2D object g, which we will print.

CODE
g.translate(pf.getImageableX(), pf.getImageableY());


This modifies the Graphics2D object to make its origin (0, 0) match the corner of the imageable area (the area of the page we can print on) so we don't print for nothing in an area.

CODE
g.drawString ("Hello world", 100, 100);


This draws the Hello World string to the point (100, 100) of the page's imageable area.

CODE
return PAGE_EXISTS;


The page exists, it is the index 0 (it can't be greaten than 0, because the first line would have blocked it. Now here's the full code:
CODE

public int print(Graphics gx, PageFormat pf, int page) throws PrinterException {
    if (page>0){return NO_SUCH_PAGE;} //Only one page
    Graphics2D g = (Graphics2D)gx; //Cast to Graphics2D object
    g.translate(pf.getImageableX(), pf.getImageableY()); //Match origins to imageable area
    g.drawString ("Hello world", 100, 100); //Print Hello World at offset (100, 100)
    return PAGE_EXISTS; //Page exists (offsets start at zero!)
}


We are finished with code code writing!

Putting it all together

Think you followed all correctly? Compare your code with this one:

CODE
//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;

public class Program1{
    //Static swing components
    static JFrame frmMain;
    static Container pane;
    static JButton btnPrint;

    public static void main (String[] args){
        //Apply system look and feel
        try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
              catch (Exception e){}
        
        //Create and resize frame
        frmMain = new JFrame ("Sample printing application");
        frmMain.setSize(300, 200); //300x200 pixels
        pane = frmMain.getContentPane();
        pane.setLayout(null); //Use null layout

        //Create components
        btnPrint = new JButton ("Print"); //Create our button

        //Add components to pane
        pane.add(btnPrint);

        //Set components' bounds
        btnPrint.setBounds(5, 5, 100, 25); //Arguments: x, y, width, height

        //Make frame visible
        frmMain.setVisible(true);

        //Add the button's action
        btnPrint.addActionListener(new btnPrintAction());
    }

    public static class btnPrintAction implements ActionListener, Printable{
        public int print(Graphics gx, PageFormat pf, int page) throws PrinterException {
            if (page>0){return NO_SUCH_PAGE;} //Only one page
            Graphics2D g = (Graphics2D)gx; //Cast to Graphics2D object
            g.translate(pf.getImageableX(), pf.getImageableY()); //Match origins to imageable area
            g.drawString ("Hello world", 100, 100); //Print Hello World at offset (100, 100)
            return PAGE_EXISTS; //Page exists (offsets start at zero!)
        }
        public void actionPerformed(ActionEvent e) {
            PrinterJob job = PrinterJob.getPrinterJob(); //Get the printer's job list
            job.setPrintable(this); //We print with this class (btnPrintAction, which implements Printable)
            if (job.printDialog() == true) { //If we clicked OK in the print dialog
                try {job.print();} catch (PrinterException ex){
                    //It did not work (PrinterException thrown), so add any error handling routines.
                }
            }
        }
    }
}


If you have this code, run the program. Click the button. Watch as the printer prints a beautiful sheet with a Hello World in black!

Extending these features

More advanced features can be used. You may try the setFont, drawImage, and many other methods. Explore the Graphics2D methods and you will find for sure all the features you will ever need.

Conclusion

This is it for the printing tutorial. I hope you learned some printing basics, and feel free explore all the Graphics2D methods. If you have any questions regarding this tutorial, contact me.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

malqa053
*



post 5 Jun, 2007 - 09:20 PM
Post #2
Thanks for the great work icon_up.gif ,
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 12/1/08 10:41PM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month