import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;
public class PrintTestFrame extends JFrame implements ActionListener, Printable
{
private PrinterJob job;
private JButton buttonPrint;
public PrintTestFrame ()
{
super ("Print Test");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setSize (300, 300);
buttonPrint = new JButton ("PRINT");
buttonPrint.addActionListener (this);
add (buttonPrint, BorderLayout.SOUTH);
job = PrinterJob.getPrinterJob ();
job.setPrintable (this);
}
public void actionPerformed (ActionEvent ae)
{
if (job.printDialog ())
{
try {
job.print ();
} catch (Exception e) {
JOptionPane.showMessageDialog (this, "Errore");
}
}
}
public int print (Graphics g, PageFormat pageFormat, int pageIndex)
{
if (pageIndex > 0)
return NO_SUCH_PAGE;
double imageableWidth = pageFormat.getImageableWidth ();
double imageableHeight = pageFormat.getImageableHeight ();
double frameWidth = getWidth ();
double frameHeight = getHeight ();
double scale = imageableWidth / frameWidth; // Modo "Fit width"
Graphics2D g2d = (Graphics2D) g;
g2d.translate (pageFormat.getImageableX (), pageFormat.getImageableY ());
g2d.scale (scale, scale);
printAll (g); // Invoca printAll sul frame (this)
return PAGE_EXISTS;
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
PrintTestFrame f = new PrintTestFrame ();
f.setVisible (true);
}
});
}
}