Skip to Main Content

Java SE (Java Platform, Standard Edition)

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!

Printing JPanel

843805Jul 31 2006 — edited Aug 1 2006
Hi,

I hope I found the right area. This is my first time printing in Java and I'm having some difficulty. I've searched but I haven't found a solution to the problem I'm having which is probably just a sequence of events issue.

I'm trying to print a JPanel which is 270x170 pixels. I have the print functionality working but for some reason the component isn't printed on the first page. It only prints a narrow rectangle of the JPanel. The next page has the JPanel printed correctly.

I've tried to figure out why it's happening but I'm totally stumped. It seems that when the print button is clicked that the print() method gets called twice. The first time through it prints that funky rectangle and the second time it prints correctly. I tried to make the method only print the second page as a work around but I end up with a blank page first.

I created a test project to simulate what my actual code does because the actual code is much to large to print here. Also, to minimize the length I've not shown the includes or package declarations. I've also removed empty abstract methods.
*********** Main User Interface Class ************
public class ComponentPrintingTestUI extends JFrame implements MouseListener {
    
    private static MyTextPane myTextPane;
    private static MyJPanel myJPanel;
    
    public ComponentPrintingTestUI() {
        initComponents();
    }
    
    private void initComponents() {
        JFrame frame = new JFrame("ComponentPrintingTest");

        //JPanel contentPanel1 = new JPanel();
        //JPanel contentPanel2 = new JPanel();
        JPanel contentPanel3 = new JPanel();
        JPanel contentPanel4 = new JPanel();
        
        contentPanel3.setMaximumSize(new Dimension(270,170));
        contentPanel3.setMinimumSize(new Dimension(270,170));
        contentPanel3.setPreferredSize(new Dimension(270,170));
        
        //JButton textPrint = new JButton("Print TextPane");
        //textPrint.addMouseListener(this);
        JButton panelPrint = new JButton("Print JPanel");
        panelPrint.addMouseListener(this);
        //myTextPane = new MyTextPane();
        //myTextPane.setEditable(false);
        myJPanel = new MyJPanel();

        //contentPanel1.add(myTextPane, BorderLayout.CENTER);
        //contentPanel2.add(textPrint, BorderLayout.CENTER);
        contentPanel3.add(myJPanel, BorderLayout.CENTER);
        contentPanel4.add(panelPrint, BorderLayout.CENTER);
        
        //frame.add(contentPanel1, BorderLayout.NORTH);
        //frame.add(contentPanel2, BorderLayout.CENTER);
        frame.add(contentPanel3, BorderLayout.NORTH);
        frame.add(contentPanel4, BorderLayout.SOUTH);
        
        frame.setSize(1280,1024);
        frame.setVisible(true);
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public void mouseClicked(MouseEvent arg0) {
        // EditorFrame extends JFrame and has all the, well, editing stuff
        //EditorFrame frame = ClerkUtilities.getEventSourceFrame(e); // method simply grabs the source frame
        //PrintableTextPane tp = frame.getTextPane();
            
        PrinterJob printJob = PrinterJob.getPrinterJob();
        //PageFormat pf = printJob.defaultPage();
        //pf.setOrientation(PageFormat.LANDSCAPE);
        printJob.setPrintable(myJPanel);
        if (printJob.printDialog())
        {
            try
            {
                printJob.print();
            } // end try
            catch (Exception ex)
            {
                ex.printStackTrace();
            } // end Exception catch
        } // end if

    }


*********** Custom JPanel Class *************
public class MyJPanel extends JPanel implements Printable {

    public MyJPanel() {
        initComponents();
    }

    private void initComponents() {
        this.setMaximumSize(new Dimension(270,170));
        this.setMinimumSize(new Dimension(270,170));
        this.setPreferredSize(new Dimension(270,170));
        this.setBackground(Color.GRAY);
    }

    public void paint(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawString("Sample drawstring", 20, 20);
        g2.drawString("Bottom line", 20, 150);
    }

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException 
        {
            /* get component width and table height */
            Dimension dimension = this.getSize();
            double compWidth = dimension.width;
            double compHeight = dimension.height;
            System.out.println("Comp width: " + compWidth);
            System.out.println("Comp height: " + compHeight);
            
            Paper card = pageFormat.getPaper();
            card.setImageableArea(0, 0, 153, 243);
            card.setSize(153,243);
            
            pageFormat.setPaper(card);
            pageFormat.setOrientation(PageFormat.LANDSCAPE);

            /* get page width and page height */
            //double pageWidth = pageFormat.getImageableWidth();
            //double pageHeight = pageFormat.getImageableHeight();
            //double scale = pageWidth / compWidth;
            //double scale = compWidth / pageWidth;
            //System.out.println("Page width: " + pageWidth);
            //System.out.println("Page height: " + pageHeight);
            //System.out.println("Scale: " + scale);
            
            /* calculate the no. of pages to print */
            //final int totalNumPages= (int)Math.ceil((scale * compHeight) / pageHeight);
            if (pageIndex > 3)
            {
                System.out.println("Total pages: " + pageIndex);
                return(NO_SUCH_PAGE);
            } // end if
            else
            {
                Graphics2D g2d = (Graphics2D)g;
                g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                System.out.println("Coords: " + pageFormat.getImageableX() + ", " + pageFormat.getImageableY());
                g2d.translate( 0f, 0f );
                //g2d.translate( 0f, -pageIndex * pageHeight );
                //g2d.scale( scale, scale );
                this.paint(g2d);
                return(PAGE_EXISTS);
            } // end else
        } // end print()

}

*********** Starter Class **********
public class ComponentPrintingTest {

    /**
     * @param args
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ComponentPrintingTestUI ui = new ComponentPrintingTestUI();
                //ui.setVisible(true);
            }
        });
    }
}
It compiles and runs...it also prints like I mentioned above. If there's any other information I can provide please let me know. I'd appreciate someone showing me the error of my ways because I've been trying to figure this out for a week and I'm REALLY frustrated.

Thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 29 2006
Added on Jul 31 2006
4 comments
675 views