Javaで印刷

プリンタへの印刷

 このページでは、Javaのプログラミングを解説した記事や書籍でほとんど触れられることのない、「印刷」をテーマにします。

プログラムの例

 Javaが印刷の機能をサポートしたのはJDK1.1からです。それは、PrintJobという抽象クラスで実現されています。抽象クラスであるということは、これのインスタンスを直接生成するのではなく、何らか別の方法を使ってインスタンスをえることになります。具体的には、ToolkitのgetPrintJob()メソッドを使ってインスタンスを取得します。

 以下がプログラムの例です。このプログラムはアプリケーション形式で動きます。

プログラムの動きとして、入力フィールドを2つ、チェックボックスを1つ用意し、また、「印刷」とラベルを書いたボタンを一つ用意します。この「印刷」というボタンを押すと、そのプログラムのウィンドウの中身(frame)を丸ごと印字します。

import java.awt.*;
import java.awt.event.*;
import java.util.*;
 
public class testPrintJob implements ActionListener {
	TextField	theField1;
	TextField	theField2;
	Checkbox	theCheck;
	Button		thePrintButton;
	Frame 		theFrame;
	Panel		thePanel;
	
	public void init() {
		System.err.println("init() called.");
 
		theFrame = new Frame();
		thePanel = new Panel();
 
		thePanel.add(theField1 = new TextField(10));
		thePanel.add(theField2 = new TextField(20));
		thePanel.add(theCheck = new Checkbox("Test"));
 
		thePanel.add(thePrintButton = new Button("印刷"));
		thePrintButton.addActionListener(this);
		
		theFrame.add(thePanel);
		theFrame.show();
	}
	
	public void actionPerformed(ActionEvent evt) {
		PrintJob thePrintJob =
			Toolkit.getDefaultToolkit().getPrintJob(theFrame, "Print Test", (Properties)null);
		if (thePrintJob != null) {
			Graphics theGtoPrint = thePrintJob.getGraphics();
			System.err.println("getPageDimension() = " + thePrintJob.getPageDimension());
			System.err.println("getPageResolution() = " + thePrintJob.getPageResolution());
			theFrame.printAll(theGtoPrint);			
			thePrintJob.end();
		}
	}
 
	public static void main(String args[]) {
		testPrintJob theJob = new testPrintJob();
		
		theJob.init();
	}
}
 

印刷の問題点

印刷自体はうまく行きますが、いくつかの問題が発生します。

メールはこちらまで