有谁能帮助在Java程序中打印JFrame及其所有组件 [英] Can any one help Printing a JFrame with all its component in Java program

查看:37
本文介绍了有谁能帮助在Java程序中打印JFrame及其所有组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好, 现在,我面临着一个严重的问题.我已经制作了一个Java程序,需要打印该程序的JFrame之一.但是我做不到. 我已经在网上搜索了,但是我发现的代码仅打印第一个元素,这意味着只有一个元素可能是JLabel或JTextBox.但是我需要用所有数据打印整个页面.

有人可以帮助我吗?

谢谢

解决方案

将此代码附加到您的班级.希望对您有帮助

首先实现Java类的Printable接口

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

实现Printable接口后,重写方法print()

现在确定要打印的内容.以这样一种方式编写代码,即所有组件都必须位于一个父JPanel(parentPanel)上.现在,在上面的代码中,在注释旁边给出parentPanel.print(g).这将在该parentPanel上打印所有组件.

现在我们告诉Java程序要打印什么,但是要完成此打印工作,我们必须创建PrinterJob

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

将此代码放在打印按钮的ActionListener中.

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

解决方案

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.

这篇关于有谁能帮助在Java程序中打印JFrame及其所有组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆