Home Java Example Java Swing Print Screen Using Java Swing

Related Tutorials


 
 

Share on Google+Share on Google+

Print Screen Using Java Swing

Advertisement
In this section, you will learn how to print in java swing. The printable that is passed to setPrintable must have a print method that describes how to send drawing to the printer.

Print Screen Using Java Swing

     

In this section, you will learn how to print in java swing. The printable that is passed to setPrintable must have a print method that describes how to send drawing to the printer. To start drawing the Graphics object to Graphics2D, scale the resolution to the printer, and call the component's paint method with this scaled Graphics2D.

Here is the code of this program:

 

Step 1: Create "PrintExample.java" file for displaying frame.

 

 

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.print.*;
import java.awt.geom.*;

public class PrintExample extends JFrame implements ActionListener {
  public static void main(String[] args) {
    new PrintExample();
  }

  public PrintExample() {
    super("Printing Swing Components");
    WindowShow.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    JButton printButton = new JButton("Print");
    printButton.addActionListener(this);
    JPanel buttonPanel = new JPanel();
    buttonPanel.setBackground(Color.white);
    buttonPanel.add(printButton);
    content.add(buttonPanel, BorderLayout.SOUTH);
    DrawingPane drawingPanel = new DrawingPane();
    content.add(drawingPanel, BorderLayout.CENTER);
    setSize(800,300);
    setVisible(true);
  }
  
  public void actionPerformed(ActionEvent event) {
    PrintableDocument.printComponent(this);
  }
  
  class DrawingPane extends JPanel {
    private int fontSize = 90;
    private String message = "Roseindia.net";
    private int messageWidth;
    
    public DrawingPane() {
      setBackground(Color.white);
      Font font = new Font("Serif", Font.PLAIN, fontSize);
      setFont(font);
      FontMetrics metrics = getFontMetrics(font);
      messageWidth = metrics.stringWidth(message);
      int width = messageWidth*5/3;
      int height = fontSize*3;
      setPreferredSize(new Dimension(width, height));
    }
    
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D graph = (Graphics2D)g;
      int x = messageWidth/10;
      int y = fontSize*5/2;
      graph.translate(x, y);
      graph.setPaint(Color.lightGray);
      
      AffineTransform origTransform = graph.getTransform();
      graph.shear(-0.95, 0);
      graph.scale(1, 3);
      graph.drawString(message, 0, 0);
      graph.setTransform(origTransform);
      graph.setPaint(Color.black);
      graph.drawString(message, 0, 0); 
    }
  }
}

Step 2: Create "PrintableDocument.java" file for print the display value.

In this step using print() method. This method sets of pages.

PrinterJob : A PrinterJob object should be created using the static getPrinterJob() method.

The PrinterJob class is the principal class that controls printing. An application calls method in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job.

Graphic2D:

This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for rendering 2-dimensional shapes, text and images on the Java platform.

import java.awt.*;
import javax.swing.*;
import java.awt.print.*;

public class PrintableDocument implements Printable {
  private Component compent;
  
  public static void printComponent(Component c) {
    new PrintableDocument(c).print();
  }
  
  public PrintableDocument(Component compent) {
    this.compent = compent;
  }
  
  public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if(printJob.printDialog())
      try {
      printJob.print();
    }
    catch(PrinterException pe) {
      System.out.println("Error printing: " + pe);
    }
  }
  
  public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
      return(NO_SUCH_PAGE);
    }
    else {
      Graphics2D graph = (Graphics2D)g;
      graph.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
      disableBuffering(compent);
      compent.paint(graph);
      enableBuffering(compent);
      return(PAGE_EXISTS);
    }
  }
  
  public static void disableBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
  }
  
  public static void enableBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
  }
}

Step 3: Create "WindowShow.java"  file for window Look and Feel.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class WindowShow { 

  public static void setNativeLookAndFeel() {
    try{
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
  }
  
  public static JFrame openInJFrame
     (Container content, int width, int height, String title, Color bgColor) {
    class ExitListener extends WindowAdapter {
      public void windowClosing(WindowEvent event) {
        System.exit(0);
      }
    }
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.addWindowListener(new ExitListener());
    frame.setVisible(true);
    return(frame);
  }
  
  public static JFrame openInJFrame
                     (Container content, int width, int height, String title) { 
    return(openInJFrame(content, width, height, title, Color.green));
  }
  
  public static JFrame openInJFrame(Container content, int width, int height) {
    return(openInJFrame(content, width, height,content.getClass().getName(), Color.green));
  }
}

Here is the Output of this program.

 

Here download Application:

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 27, 2008

Related Tutorials

Discuss: Print Screen Using Java Swing   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:4
Ravikumar Natarajan
June 16, 2011
Print the Document By Using Printer

Thanks !,The printer code help me efficently. once again thanks.........................
milad
July 11, 2012
ask

i have tried your code to print my form , but i get a very strange error, "java platform SE binary has stopped working " and the details: Problem signature: Problem Event Name: BEX Application Name: java.exe Application Version: 7.0.30.5 Application Timestamp: 4f2cba00 Fault Module Name: NitroGraphics.dll Fault Module Version: 0.3.1.8 Fault Module Timestamp: 4aa9a06a Exception Offset: 00001fbe Exception Code: c0000409 Exception Data: 00000000 OS Version: 6.1.7600.2.0.0.256.1 Locale ID: 10241 Additional Information 1: 0f0f Additional Information 2: 0f0f7be9ee96c80e48b47ce0a1884d72 Additional Information 3: e968 Additional Information 4: e968a84802e6b05b3148dd88f9677ef8 any help ?
Md. Emran Hossain
April 25, 2013
Thank you

Thank you for your very important tutorials. My wish, you submit more tutorial about access database using Java Swing(also show Next button , previous button ) and JTable(delete, edit, no edit, difference color one by one row) Thank you again.... Emran
Zubin Sharma
August 3, 2013
Error in Print Code

it shows 1 error if I run PrintExample Class from command prompt addWindowListener(new ExitListerner()); symbol: class ExitListener location PrintExample 1 error
DMCA.com