Page 1 of 1

java printing print Hello World Rate Topic: -----

#1 alpha02  Icon User is offline

  • Sexy DIC God
  • member icon

Reputation: 47
  • View blog
  • Posts: 803
  • Joined: 20-May 06

Posted 03 June 2007 - 06:33 PM

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:

//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:

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:

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:

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.*.

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:

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:

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.

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.

Graphics2D g = (Graphics2D)gx;


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

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.

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


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

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:
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:

//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.

Is This A Good Question/Topic? 4
  • +

Replies To: java printing

#2 malqa053  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-October 06

Posted 05 June 2007 - 10:20 PM

Thanks for the great work :^: ,
Was This Post Helpful? 0
  • +
  • -

#3 Guest_H G*


Reputation:

Posted 17 January 2011 - 05:49 PM

This code is for only printing "Hello World", how would the code change if you wanted to print out a whole GUI window frame?
Was This Post Helpful? 0

#4 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10781
  • View blog
  • Posts: 40,153
  • Joined: 27-December 08

Posted 17 January 2011 - 10:19 PM

The GUI Components have print() methods that will do this.
Was This Post Helpful? 1
  • +
  • -

#5 Bocard  Icon User is offline

  • D.I.C Head

Reputation: 15
  • View blog
  • Posts: 223
  • Joined: 24-September 08

Posted 05 February 2011 - 05:30 AM

I am trying to print the whole frame, I followed this tutorial and macosxnerd's advice but all the output I get is a JMenu printed, instead of the whole frame.

Any ideas what's not going as it should?
Was This Post Helpful? 0
  • +
  • -

#6 hawary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 08-March 12

Posted 07 June 2012 - 05:57 PM

what if i print a Jpanel that contain a Jlabels, Jtextfields, and Jtable
the page is printed but the problem is the Jtable not fully printed if it have alot of rows and the scroll is running
what should i do?
Was This Post Helpful? 0
  • +
  • -

#7 GunnerInc  Icon User is offline

  • "Hurry up and wait"
  • member icon




Reputation: 858
  • View blog
  • Posts: 2,302
  • Joined: 28-March 11

Posted 07 June 2012 - 06:03 PM

@hawary, this a tutorial section, if you have a problem with your code please post the question in the proper forum section.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1