Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用java打印jframe_Java_Swing - Fatal编程技术网

用java打印jframe

用java打印jframe,java,swing,Java,Swing,我想在单击按钮时打印jframe 所以我尝试了这个代码。如果我点击打印按钮,我会看到一个打印机对话框,当我告诉它打印时,它只打印一个空白文档,我不知道为什么。有什么帮助吗 public static class Printer implements Printable { final Component comp; public Printer(Component comp){ this.comp = comp; } @Override

我想在单击按钮时打印jframe

所以我尝试了这个代码。如果我点击打印按钮,我会看到一个打印机对话框,当我告诉它打印时,它只打印一个空白文档,我不知道为什么。有什么帮助吗

public static class Printer implements Printable {
    final Component comp;

    public Printer(Component comp){
        this.comp = comp;
    }

    @Override
    public int print(Graphics g, PageFormat format, int page_index)
            throws PrinterException {
        if (page_index > 0) {
            return Printable.NO_SUCH_PAGE;
        }

        // get the bounds of the component
        Dimension dim = comp.getSize();
        double cHeight = dim.getHeight();
        double cWidth = dim.getWidth();

        // get the bounds of the printable area
        double pHeight = format.getImageableHeight();
        double pWidth = format.getImageableWidth();

        double pXStart = format.getImageableX();
        double pYStart = format.getImageableY();

        double xRatio = pWidth / cWidth;
        double yRatio = pHeight / cHeight;

        Graphics2D g2 = (Graphics2D) g;
        g2.translate(pXStart, pYStart);
        g2.scale(xRatio, yRatio);
        comp.paint(g2);

        return Printable.PAGE_EXISTS;
    }
}
在执行的按钮操作中

 JFrame yourComponent = new ODietListJFrame();
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat preformat = pjob.defaultPage();
    preformat.setOrientation(PageFormat.LANDSCAPE);
    PageFormat postformat = pjob.pageDialog(preformat);

    //If user does not hit cancel then print.
    if (preformat != postformat) {
        //Set print component
        pjob.setPrintable(new Printer(yourComponent), postformat);
        if (pjob.printDialog()) {
            try {
                pjob.print();
            } catch (PrinterException ex) {
                Logger.getLogger(ODietListJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

谢谢你的帮助。

首先,不要叫画画,叫打印我试过一次叫打印,又一次叫打印全部,但什么都没变你试过先让画框可见吗?不幸的是,我是初学者,你能告诉我如何让画框可见吗?如果你想使用setvisible,那么是的,我会这么做。