Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Here is a free Java Print Preview Class

807580Mar 1 2005 — edited Sep 2 2009
Ok, for 2 weeks now ive been in agony trying to program a
print preview for a program im writing for work.
Alot, of the free print previews online are way complicated
and crazy and hard to implement.
Either that, or these forums and "how tos" online never
answered the question or were to general or hard
to follow for a beginner.
I even posted a $40 question on google answers on how to
do this and never got an answer.
If ive had this problem others must have also
so to save them the trouble i went through, here is a good
starting point.

I just finished this class.
All you have to do is pass it a JPanel (or i guess any component
with a " .paint(Graphics g) " ).
new PrintPreview( component );
please, i encourage comments and polite criticism.
im just starting out so i know this isnt perfect but i posted
it with good intentions.
Hope it helps out some out there.

---------------------------------------------------
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;

import java.awt.print.*;
import java.lang.Math.*;

import java.awt.image.*;


public class PrintPreview extends JInternalFrame implements ActionListener{

public PrintPreview(Component pc){

	super("Print Preview", true, true, true, true);

	PC = pc;

// buttons

	pf1 = new JRadioButton("Portrait");
   	pf1.setActionCommand("1");
   	pf1.setSelected(true);

   	pf2 = new JRadioButton("Landscape");
   	pf2.setActionCommand("2");


   	pf.add(pf1);
   	pf.add(pf2);

   	pf1.setBackground(Pref.tbgc);
   	pf2.setBackground(Pref.tbgc);
   	cp.setBackground(Pref.tbgc);


	preview.addActionListener(this);
   	print.addActionListener(this);


// set

	pp.setPreferredSize(new Dimension(460, 460));
	pp.setBorder(BorderFactory.createLineBorder (Color.black, 2));
	pp.setBackground(Pref.tbgc);


	hold.setPreferredSize(new Dimension(200, 280));
	hold.setBorder(BorderFactory.createLineBorder (Color.black, 2));
	hold.setBackground(Pref.tbgc);


// make main panel


	mp.setBackground(Pref.tbgc);

	GridBagLayout gridbag = new GridBagLayout();
 	GridBagConstraints constraints = new GridBagConstraints();

	mp.setLayout(gridbag);

// make hold panel


	GridBagLayout g1 = new GridBagLayout();
 	GridBagConstraints c1 = new GridBagConstraints();

	hold.setLayout(g1);

// DELETE


	PF.setOrientation(PF.PORTRAIT);



// GUI

// hold

	c1.insets.top = 5;
	c1.insets.left = 45;
	c1.insets.right = 5;


	buildConstraints(c1, 0, 2, 2, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(pf1, c1);

	hold.add(pf1);



	c1.insets.top = 2;

	buildConstraints(c1, 0, 4, 2, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(pf2, c1);

	hold.add(pf2);

//
	c1.insets.left = 5;
	c1.insets.right = 0;
	c1.insets.top = 25;

	buildConstraints(c1, 0, 6, 1, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(xsl, c1);

	hold.add(xsl);

	c1.insets.left = 0;
	c1.insets.right = 5;

	buildConstraints(c1, 1, 6, 1, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(xs, c1);

	hold.add(xs);

//
	c1.insets.left = 5;
	c1.insets.right = 0;
	c1.insets.top = 5;

	buildConstraints(c1, 0, 8, 1, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(ysl, c1);

	hold.add(ysl);

	c1.insets.left = 0;
	c1.insets.right = 5;

	buildConstraints(c1, 1, 8, 1, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(ys, c1);

	hold.add(ys);

	c1.insets.left = 25;
	c1.insets.right = 5;

	buildConstraints(c1, 0, 10, 2, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(cp, c1);

	hold.add(cp);

//

	c1.insets.left = 35;
	c1.insets.right = 35;
	c1.insets.top = 20;

	buildConstraints(c1, 0, 12, 2, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(ftp, c1);

	hold.add(ftp);


	c1.insets.left = 35;
	c1.insets.right = 35;
	c1.insets.top = 25;

	buildConstraints(c1, 0, 14, 2, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(preview, c1);

	hold.add(preview);

	c1.insets.bottom = 15;
	c1.insets.top = 5;

	buildConstraints(c1, 0, 16, 2, 1, 1, 1);
	c1.fill = GridBagConstraints.BOTH;
	g1.setConstraints(print, c1);

	hold.add(print);

//

	constraints.insets.top = 10;
	constraints.insets.left = 10;
	constraints.insets.bottom = 10;


	buildConstraints(constraints, 0, 2, 1, 1, 1, 1);
	constraints.fill = GridBagConstraints.NONE;
	gridbag.setConstraints(hold, constraints);

	mp.add(hold);

	constraints.insets.right = 10;


	buildConstraints(constraints, 1, 2, 1, 1, 1, 1);
	constraints.fill = GridBagConstraints.NONE;
	gridbag.setConstraints(pp, constraints);

	mp.add(pp);




// display

	this.setContentPane(mp);

	this.setVisible(true);
	this.setResizable(false);

	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	setSize(720, 520);

   	Dimension windowSize = getSize();
	setLocation(Math.max(0,(screenSize.width -windowSize.width)/2),
        (Math.max(0,(screenSize.height-windowSize.height)/2)));

   	MercPlot.desktop.add(this);

   	try {
	this.setSelected(true);
   	} catch (java.beans.PropertyVetoException e) {}

}

public void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, double wx, double wy){

	gbc.gridx = gx;
	gbc.gridy = gy;
	gbc.gridwidth = gw;
	gbc.gridheight = gh;
	gbc.weightx = wx;
	gbc.weighty = wy;

}

public class PreviewPage extends JPanel{

public PreviewPage(){

}

public void paint(Graphics g){

	super.paint(g);
	Graphics2D g2 = (Graphics2D)g;

// PORTRAIT

	if(PF.getOrientation() == PF.PORTRAIT){

	g.setColor(Color.black);
	g.drawRect(60, 10, 340, 440);

	int x1 = (int)Math.rint( ( (double)PF.getImageableX() / 72 ) * 40 );
	int y1 = (int)Math.rint( ( (double)PF.getImageableY() / 72 ) * 40 );

	int l1 = (int)Math.rint( ( (double)PF.getImageableWidth() / 72 ) * 40 );
	int h1 = (int)Math.rint( ( (double)PF.getImageableHeight() / 72 ) * 40 );

	g.setColor(Color.red);
	g.drawRect(x1+60, y1+10, l1, h1);

	setScales();

	int x2 = (int)Math.rint( 1028 / XSC );
	int y2 = (int)Math.rint( 768 / YSC );


	Image image = new BufferedImage( x2, y2, BufferedImage.TYPE_INT_ARGB);

	PC.paint( image.getGraphics() );

	g.drawImage(image, x1+60, y1+10, l1, h1, this);





	}

// LANDSCAPE

	if(PF.getOrientation() == PF.LANDSCAPE){

	g.setColor(Color.black);
	g.drawRect(10, 60, 440, 340);

	int x1 = (int)Math.rint( ( (double)PF.getImageableX() / 72 ) * 40 );
	int y1 = (int)Math.rint( ( (double)PF.getImageableY() / 72 ) * 40 );

	int l1 = (int)Math.rint( ( (double)PF.getImageableWidth() / 72 ) * 40 );
	int h1 = (int)Math.rint( ( (double)PF.getImageableHeight() / 72 ) * 40 );

	g.setColor(Color.red);
	g.drawRect(x1+10, y1+60, l1, h1);

	setScales();

	int x2 = (int)Math.rint( 1028 / XSC );
	int y2 = (int)Math.rint( 768 / YSC );


	Image image = new BufferedImage( x2, y2, BufferedImage.TYPE_INT_ARGB);

	PC.paint( image.getGraphics() );

	g.drawImage(image, x1+10, y1+60, l1, h1, this);


	}


}

	Graphics P;

}

public void actionPerformed(ActionEvent e){


// fit to page
	if(e.getSource() == ftp){

	}

// preview
	if(e.getSource() == preview){

	setProperties();
	}


// print
	if(e.getSource() == print){
	doPrint();
	}

}

public void setProperties(){

	if(pf1.isSelected() == true){
	PF.setOrientation(PF.PORTRAIT);
	}

	if(pf2.isSelected() == true){
	PF.setOrientation(PF.LANDSCAPE);
	}

	setScales();

	pp.repaint();

}

public void setScales(){

	try{
	XSC = Double.parseDouble( xs.getText() );
	} catch (NumberFormatException e) { }

	try{
	YSC = Double.parseDouble( ys.getText() );
	} catch (NumberFormatException e) { }


}

public void doPrint(){

	PrintThis();

}

public void PrintThis(){

	PrinterJob printerJob = PrinterJob.getPrinterJob();

	Book book = new Book();
	book.append( new PrintPage(), PF );

	printerJob.setPageable(book);

	boolean doPrint = printerJob.printDialog();
	if (doPrint) {

	try {
	printerJob.print();
	} catch (PrinterException exception) {
	System.err.println("Printing error: " + exception);
	}

	}

}

public class PrintPage implements Printable{

public int print(Graphics g, PageFormat format, int pageIndex) {



	Graphics2D g2D = (Graphics2D) g;

	g2D.translate(format.getImageableX (), format.getImageableY ());

	disableDoubleBuffering(mp);

	System.out.println("get i x " + format.getImageableX ());
	System.out.println("get i x " + format.getImageableY ());
	System.out.println("getx: " + format.getImageableWidth() );
	System.out.println("getx: " + format.getImageableHeight() );



	// scale to fill the page
	double dw = format.getImageableWidth();
	double dh = format.getImageableHeight();
	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

	setScales();

	double xScale = dw / (1028/XSC);
	double yScale = dh / (768/YSC);
	double scale = Math.min(xScale,yScale);



	System.out.println("" + scale);

	g2D.scale( xScale, yScale);


	((JPanel)PC).paint(g);

	enableDoubleBuffering(mp);


	return Printable.PAGE_EXISTS;

}

public void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
}

public void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
}

}


	Component PC;

	PageFormat PF = new PageFormat();

	double XSC = 1;
	double YSC = 1;

// gui comp

	JPanel mp = new JPanel();
	JPanel hold = new JPanel();
	JPanel pp = new PreviewPage();

	ButtonGroup pf = new ButtonGroup();
	JRadioButton pf1;
	JRadioButton pf2;

	JLabel xsl = new JLabel("X Scale:", JLabel.LEFT);
	JTextField xs = new JTextField("1");

	JLabel ysl = new JLabel("Y Scale:", JLabel.LEFT);
	JTextField ys = new JTextField("1");

	JButton ftp = new JButton("Fit to Page");
	JCheckBox cp = new JCheckBox("Constrain Proportions");

	JButton preview = new JButton("PREVIEW");
	JButton print = new JButton("PRINT");


}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 30 2009
Added on Mar 1 2005
20 comments
398 views