PrintSampleApp.java Source code

Java tutorial

Introduction

Here is the source code for PrintSampleApp.java

Source

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.util.Properties;

import javax.swing.JFrame;

public class PrintSampleApp extends JFrame {
    MyCanvas canvas = new MyCanvas();

    public static void main(String args[]) {
        PrintSampleApp app = new PrintSampleApp();
    }

    public PrintSampleApp() {
        add("Center", canvas);
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        String name = "Test print job";
        Properties properties = new Properties();
        PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(PrintSampleApp.this, name, properties);
        if (pj != null) {
            canvas.printAll(pj.getGraphics());
            pj.end();
        }
    }
}

class MyCanvas extends Canvas {
    public void paint(Graphics g) {
        Dimension size = getSize();
        int width = size.width;
        int height = size.height;
        int x1 = (int) (width * 0.1);
        int x2 = (int) (width * 0.9);
        int y1 = (int) (height * 0.1);
        int y2 = (int) (height * 0.9);
        g.drawRect(x1, y1, x2 - x1, y2 - y1);
        g.drawOval(x1, y1, x2 - x1, y2 - y1);
        g.drawLine(x1, y1, x2, y2);
        g.drawLine(x2, y1, x1, y2);
        String text = "Print Me! ";
        text += text;
        text += text;
        g.drawString(text, x1, (int) ((y1 + y2) / 2));
        g.dispose();
    }
}