Shapes Print
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.RoundRectangle2D;
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;
public class ShapesPrint extends JPanel implements Printable, ActionListener {
final static JButton button = new JButton("Print");
public ShapesPrint() {
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog()) {
try {
printJob.print();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShapes(g2);
}
public void drawShapes(Graphics2D g2) {
g2.fill(new RoundRectangle2D.Double(10, 10, 200, 200, 10, 10));
}
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if (pi >= 1) {
return Printable.NO_SUCH_PAGE;
}
drawShapes((Graphics2D) g);
return Printable.PAGE_EXISTS;
}
public static void main(String s[]) {
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
};
JFrame f = new JFrame();
f.addWindowListener(l);
JPanel panel = new JPanel();
panel.add(button);
f.getContentPane().add(BorderLayout.SOUTH, panel);
f.getContentPane().add(BorderLayout.CENTER, new ShapesPrint());
f.setSize(580, 500);
f.show();
}
}
Related examples in the same category