final JPanel panel = new JPanel();
// layout your panel as desired...
// set the size & location of the panel
panel.setLocation(0, 0);
panel.setSize(500, 400);
PrinterJob job = PrinterJob.getPrinterJob();
// set the Printable to the PrinterJob
job.setPrintable(new Printable() {
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
if (pageIndex == 0) {
panel.print(graphics);
return Printable.PAGE_EXISTS;
}
return Printable.NO_SUCH_PAGE;
}
});
// show the dialog
if (job.printDialog()) {
try {
job.print();
}
catch (PrinterException ex) {
// handle exception
}
}
Note that only in JDK5 can you print panels with all contents when the panel has noot been realilzed on screen. If you are working with a previous JDK version, you must first show the panel on screen and then print it.
The code may contain errors, I havn't run it.