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.

Print Screen Using Java Swing

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:

 

Tutorials

  1. Display Image in Java
  2. Show Coordinates
  3. What is Java Swing?
  4. Creating a Frame
  5. Setting an Icon for a Frame in Java
  6. Show Dialog Box in Java
  7. Show message and confirm dialog box
  8. Show input dialog box
  9. Changing the Label of a JButton Component in Java
  10. Setting Multi-Line label on the Button
  11. Setting icon on the button in Java
  12. Making a Frame Non Resizable in Java
  13. Remove Minimize and Maximize Button of Frame in Java
  14. Removing the Title Bar of a Frame
  15. Setting Bounds for a maximized frame
  16. Iconifying and Maximizing a frame in Java
  17. Making a component drag gable in java
  18. Create a ToolBar in Java
  19. Animating Images in Java Application
  20. Drawing with Color in Java
  21. Drawing with Gradient Color in Java
  22. Adding a Rollover and Pressed Icon to a JButton Component in Java
  23. Creating Check Box in Java Swing
  24. Customize the Icon in a JCheckBox Component of Java Swing
  25. Create a JComboBox Component in Java
  26. Combo Box operation in Java Swing
  27. Create a JRadioButton Component in Java
  28. Selecting a Radio Button component in Java
  29. Create a JList Component in Java
  30. Setting Tool Tip Text for items in a JList Component
  31. Setting the Dimensions of an Item in a JList Component in Java
  32. Create a JSpinner Component in Java
  33. Show Time in JSpinner Component
  34. Disabling Keyboard Editing in a JSpinner Component
  35. Limiting the Values in a Number JSpinner Component
  36. JSlider Component of Java Swing
  37. Progress Bar in Java Swing
  38. Create menus and submenus in Java
  39. Crate a Popup Menu in Java
  40. Create a Popup Menus with Nested Menus in Java