Java2D (HelloWorldPrinter)

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class HelloWorldPrinter extends JPanel implements Printable,
		ActionListener {
	private static final long serialVersionUID = -5674812845074326132L;

	public HelloWorldPrinter() {
		JButton printButton = new JButton("Print Hello World");
		printButton.addActionListener(this);
		add(printButton);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				createAndShowGUI();
			}
		});
	}

	private static void createAndShowGUI() {
		JFrame frame = new JFrame("Hello World Printer");
		frame.setContentPane(new HelloWorldPrinter());
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		PrinterJob job = PrinterJob.getPrinterJob();
		job.setPrintable(this);
		boolean ok = job.printDialog();
		if (ok) {
			try {
				job.print();
			} catch (PrinterException ex) {
				/* The job did not successfully complete */
				ex.printStackTrace();
			}
		}
	}

	@Override
	public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
			throws PrinterException {
		/* We have only one page, and 'page' is zero-based */
		if (pageIndex > 0) {
			return NO_SUCH_PAGE;
		}

		/* (0,0) is outside the imageable area, translate to avoid clipping */
		Graphics2D g2 = (Graphics2D) graphics;
		g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

		/* Now we perform our rendering */
		g2.drawString("Hello world!", 100, 100);

		/* Tell the caller that this page is part of the printed document */
		return PAGE_EXISTS;
	}
}
Java2D (HelloWorldPrinter)_第1张图片

你可能感兴趣的:(swing,JavaSE,Graphics2D,Java2D,JFC)