Print multiple JPanels

I'm just starting to learn about printing with Java Swing, so please bear with me if this question is very naive.

I have a rather complicated layout with several JPanels that contain other JPanels that contain JLabels. I want to somehow print this on a printer.

I know that I can "draw" on a Graphics2D object that represents a printed page, but for this I need to place each object separately. I would like to be able to use Swing layout managers to layout elements on my page. One way to do this is to call jp.paint(g2d) , where jp is JPanel and g2d is a Graphics2D object representing the printed page. However, as far as I can see, this will only print the JPanel, which is actually displayed on the screen. If the JPanel is not displayed, it will not be printed.

So, is there a way to build (rather complicated) JPanel and send it to the printer without first displaying JPanel on the computer screen?

Or am I on a completely wrong path here?

+2
source share
1 answer

A carved example of how to print a JPanel while invisible.

 public class TestPrinterSmall { static class JPanelPrintable extends JPanel implements Printable { public int print(Graphics g, PageFormat pf, int page) throws PrinterException { if (page > 0) return Printable.NO_SUCH_PAGE; printAll(g); return Printable.PAGE_EXISTS; } }; private static void printIt(Printable p) throws PrinterException { PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(p); if (job.printDialog()) job.print(); } public static void main(String args[]) throws PrinterException { final JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setSize(400,400); final JPanelPrintable j = new JPanelPrintable(); j.setLayout(new BorderLayout()); j.add(new JButton("1111"),BorderLayout.NORTH); j.add(new JButton("2222"),BorderLayout.SOUTH); f.add(j);f.repaint();f.pack(); //f.setVisible(true); printIt(j); } } 

Output:

 (nothing) 

A printer:

enter image description here

+2
source

All Articles