public class PrintPreview
extends JFrame
{
protected int m_wPage;
protected int m_hPage;
protected int m_orientation;
protected Printable m_target;
protected JComboBox m_cbScale;
protected PreviewContainer m_preview;
public PrintPreview(Printable target)
{
this(target, "Print Preview", PageFormat.PORTRAIT);
}
public PrintPreview(Printable target, String title, int orientation)
{
super(title);
setSize(600, 400);
getContentPane().setLayout(new BorderLayout());
m_target = target;
m_orientation = orientation;
JToolBar tb = new JToolBar();
JButton bt = new JButton("Print", new ImageIcon("print.gif"));
ActionListener lst = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
PrinterJob prnJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = prnJob.defaultPage();
pageFormat.setOrientation(m_orientation);
prnJob.setPrintable(m_target, pageFormat);
if (pageFormat.getHeight()==0 || pageFormat.getWidth()==0)
{
System.err.println("Unable to determine default page size");
return;
}
m_wPage = (int)(pageFormat.getWidth());
m_hPage = (int)(pageFormat.getHeight());
int scale = 10;
int w = (int)(m_wPage*scale/100);
int h = (int)(m_hPage*scale/100);
int pageIndex = 0;
try
{
while (true)
{
BufferedImage img = new BufferedImage(m_wPage,
m_hPage, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, m_wPage, m_hPage);
if (target.print(g, pageFormat, pageIndex) !=
Printable.PAGE_EXISTS)
break;
class PreviewContainer
extends JPanel
{
protected int H_GAP = 16;
protected int V_GAP = 10;
public Dimension getPreferredSize()
{
int n = getComponentCount();
if (n == 0)
return new Dimension(H_GAP, V_GAP);
Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();
int w = dc.width;
int h = dc.height;
Dimension dp = getParent().getSize();
int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
int nRow = n/nCol;
if (nRow*nCol < n)
nRow++;
int ww = nCol*(w+H_GAP) + H_GAP;
int hh = nRow*(h+V_GAP) + V_GAP;
Insets ins = getInsets();
return new Dimension(ww+ins.left+ins.right,
hh+ins.top+ins.bottom);
}
public Dimension getMaximumSize()
{
return getPreferredSize();
}
public Dimension getMinimumSize()
{
return getPreferredSize();
}
public void doLayout()
{
Insets ins = getInsets();
int x = ins.left + H_GAP;
int y = ins.top + V_GAP;
int n = getComponentCount();
if (n == 0)
return;
Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();
int w = dc.width;
int h = dc.height;
Dimension dp = getParent().getSize();
int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
int nRow = n/nCol;
if (nRow*nCol < n)
nRow++;
int index = 0;
for (int k = 0; k<nRow; k++)
{
for (int m = 0; m<nCol; m++)
{
if (index >= n)
return;
comp = getComponent(index++);
comp.setBounds(x, y, w, h);
x += w+H_GAP;
}
y += h+V_GAP;
x = ins.left + H_GAP;
}
}
}
class PagePreview
extends JPanel
{
protected int m_w;
protected int m_h;
protected Image m_source;
protected Image m_img;