Can any one help Printing a JFrame with all its component in Java program

爷,独闯天下 提交于 2020-01-15 02:55:59

问题


Hello everyone, Now a days i am facing a serious problem. I have made a java program and one of the JFrame of this program needs to be printed. But i can't do that. I have searched on the web but the code i have found only prints the first element means just 1 element may be JLabel or JTextBox. But i need to print the whole page with all data.

Can anyone please help me?

Thanks


回答1:


Attach this code to your class. Hope this will help you

First of all implement the Printable interface to your Java class

class ClassName extends JFrame implements Printable { //your code goes here }

After implementing Printable interface override the method print()

public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
    if (page > 0) {
        return NO_SUCH_PAGE;
    }
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    //Give the component to be printed here...
    System.out.println("Successfully printed");
    return PAGE_EXISTS;
}

Now decide what you want to print. Write your code in such a way that all the components must be on one parent JPanel(parentPanel). Now in the above code next to the comment give parentPanel.print(g) This will print all the components on that parentPanel.

Now we told out Java program what to be printed but to complete this printing job we have to create PrinterJob

PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(this); boolean ok = job.printDialog(); if (ok) { try { job.print(); } catch (PrinterException ex) { System.out.println(ex); } }

Place this code in the ActionListener of your print button.



来源:https://stackoverflow.com/questions/12584548/can-any-one-help-printing-a-jframe-with-all-its-component-in-java-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!