Hi
Following is the code for a sample application which has a simple menu and the content of the window is printed.
import javax.swing.JFrame;
import javax.swing.JEditorPane;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenuItem;
import java.awt.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet ;
public class PrintExample extends JFrame implements ActionListener,Printable
{
private JEditorPane textarea;
private JMenuBar mbar;
private JMenu print;
private JMenuItem mitem;
String str = "This is some sample text which will be printed by this program as a test for printing";
public PrintExample()
{
super("Simple Text Editor Example");
setSize(600,600);
this.getContentPane().setBackground(Color.white);
init();
show();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void init()
{
mbar = new JMenuBar();
setJMenuBar(mbar);
print = new JMenu("Print");
mitem = new JMenuItem("Print Text");
mitem.addActionListener(this);
print.add(mitem);
mbar.add(print);
textarea = new JEditorPane();
textarea.setContentType("text/plain");
textarea.setText(str);
getContentPane().add(textarea);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == mitem)
{
PrinterJob printJob = PrinterJob.getPrinterJob(); // Get a printing object
printJob.setPrintable(this); // The view is the page source
HashPrintRequestAttributeSet printAttr = new HashPrintRequestAttributeSet();
if(printJob.printDialog(printAttr)) // Display print dialog
{ // If true is returned...
try
{
printJob.print(printAttr); // then print
}
catch(PrinterException pe)
{
System.out.println(pe);
}
}
}
}
public int print(Graphics g, PageFormat pf, int index)
{
if(index>0)
return NO_SUCH_PAGE;
Graphics2D gr2 = (Graphics2D)g;
gr2.translate(pf.getImageableX(),pf.getImageableY( ));
paint(gr2);
return Printable.PAGE_EXISTS;
}
public static void main(String[] args)
{
PrintExample px = new PrintExample();
}
}
Regards and Happy New Year
Yashraj Chauhan
Java\J2EE Specialist
Wiley Support Team
|