Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Printing a JPanel



Hello,

I am trying to figure out how to print a JPanel using java.awt.print
framework. I want to print out a JPanel as it appears on the screen.
As a test I wrote a small program that brings up a print dialog when
the button is clicked. When it is printed, only a black square the
same size as my component is printed, and none of the contents are
printed. I am clearly missing something. If someone can point me in
the right direction that would be great. I have not found the online
printing tutorial at Sun all that helpful for what I want to do.

Thanks,
Jonathan
// here is my test program
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
import java.awt.event.*;

public class PrintButton extends JPanel implements
Printable, ActionListener{
JButton ok = new JButton("OK");

public PrintButton(){
ok.addActionListener(this);
this.setPreferredSize(new Dimension(400,400));
this.add(ok);
JFrame frame = new JFrame("Print");
frame.getContentPane().add(this);
frame.pack();
frame.setVisible(true);
}


public static void main(String[] args) {
new PrintButton();
}


public void actionPerformed(ActionEvent e) {


PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog()){
try{
printJob.print();
}
catch(Exception ex){
throw new RuntimeException(ex);
}
}
}


public int print(Graphics g, PageFormat pf, int index) throws
PrinterException {

Graphics2D g2 = (Graphics2D)g;
if (index >= 1){
return Printable.NO_SUCH_PAGE;
}
else {

ok.printAll(g2);
return Printable.PAGE_EXISTS;
}

}
}
_______________________________________________
java-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/java-dev
Be sure to read the FAQ http://developer.apple.com/java/faq/ before posting
Do not post admin requests to the list. They will be ignored.



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.