単純なクラスは、オブジェクトまたは JPanel を出力します。
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.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Chromaticity;
import javax.print.attribute.standard.DialogTypeSelection;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TemplateDemo extends JFrame implements Printable, ActionListener {
JButton btn;
JTextField name_txt;
JPanel panel;
public TemplateDemo() {
panel = new JPanel(null);
panel.setBounds(0, 0, 300, 300);
add(panel);
name_txt = new JTextField();
name_txt.setBounds(0, 10, 200, 20);
panel.add(name_txt);
btn = new JButton("Click");
btn.setBounds(0, 240, 200, 30);
btn.addActionListener(this);
panel.add(btn);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, 400, 400);
setLayout(null);
setVisible(true);
}
@Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
Graphics2D graphics = (Graphics2D) g;
if (pageIndex == 0) {
g.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());
panel.print(g);
return PAGE_EXISTS;
}
return NO_SUCH_PAGE;
}
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(this);
PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
set.add(Chromaticity.COLOR);
set.add(DialogTypeSelection.COMMON);
if (pj.printDialog(set)) {
try {
pj.print(set);
} catch (PrinterException ex) {
}
}
}
public static void main(String[] args) {
new TemplateDemo();
}
}