Java6学习笔记47——JAVA中的打印组件

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Component;
import java.awt.Container;
import java.awt.print.PrinterJob;
import java.awt.print.Printable;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class PrintDemo4 extends JFrame implements ActionListener {
JButton button;
public static void main(String arg[]) {
new PrintDemo4();
}
PrintDemo4() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );

Container pane = getContentPane();
BoxLayout boxlayout = new BoxLayout(pane,BoxLayout.Y_AXIS);
pane.setLayout(boxlayout);

button = new JButton("Print");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(this);
pane.add(button);

pane.add(new Marker(200,200));

pack();

setLocation(250,150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Print"))
printGUI(this);
}
public void printGUI(Component component) {
PrinterJob printerjob = PrinterJob.getPrinterJob();
ComponentPrinter printable = new ComponentPrinter(component);
printerjob.setPrintable(printable);
boolean performPrinting = printerjob.printDialog();
if(performPrinting) {
try {
printerjob.print();
System.out.println("print succeeded");
} catch(PrinterException e) {
System.out.println("print failed");
System.out.println(e);
}
} else {
System.out.println("print job cancelled");
}
}
}

class ComponentPrinter implements Printable {
private Component componentToPrint;
ComponentPrinter(Component component) {
componentToPrint = component;
}
public int print(Graphics g,PageFormat pf,int page)
throws PrinterException {
if(page > 0)
return(NO_SUCH_PAGE);

Graphics2D g2 = (Graphics2D)g;
g2.translate(pf.getImageableX(),pf.getImageableY());

componentToPrint.printAll(g2);


return(PAGE_EXISTS);
}
}

你可能感兴趣的:(java,swing)