简体   繁体   English

如何打印带有摆动组件的JPanel?

[英]How to print a JPanel with swing components?

I am trying to print a JPanel using java.awt.print.I want to print out a JPanel.I have tried the following code which consists of only one button.When printed it appears on the left corner of the page,but I need to print it in the original position as it appears on the screen.Is there way to set bounds to give an exact position? 我正在尝试使用java.awt.print打印一个JPanel。我想打印出一个JPanel。我尝试了以下仅包含一个按钮的代码。打印时它出现在页面的左上角,但是我需要可以将其打印到屏幕上显示的原始位置。是否可以设置边界以给出确切位置?

enter code here 在这里输入代码

import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
import java.awt.event.*;

public class PrintButton extends JPanel implements
        Printable, ActionListener {

    JButton ok = new JButton("OK");

    public PrintButton() {
        ok.addActionListener(this);
        this.setPreferredSize(new Dimension(400, 400));
        this.add(ok);
        JFrame frame = new JFrame("Print");
        frame.getContentPane().add(this);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new PrintButton();
    }

    public void actionPerformed(ActionEvent e) {


        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog()) {
            try {
                printJob.print();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    public int print(Graphics g, PageFormat pf, int index) throws
            PrinterException {

        Graphics2D g2 = (Graphics2D) g;
        if (index >= 1) {
            return Printable.NO_SUCH_PAGE;
        } else {

            ok.printAll(g2);
            return Printable.PAGE_EXISTS;
        }

    }
}

In your print method, you are only printing the button: 在您的print方法中,您仅打印按钮:

ok.printAll(g2);

To print the JPanel, you should call the printAll method of that JPanel: 要打印JPanel,应调用该JPanel的printAll方法:

this.printAll(g2);

If you want to be sure the panel fits on the page, you'll want to scale it using a Graphics2D transformation, based on the page size passed to you in the PageFormat object. 如果要确保面板适合页面,则需要根据在PageFormat对象中传递给您的页面大小,使用Graphics2D转换来缩放面板。

AffineTransform originalTransform = g2.getTransform();

double scaleX = pf.getImageableWidth() / this.getWidth();
double scaleY = pf.getImageableHeight() / this.getHeight();
// Maintain aspect ratio
double scale = Math.min(scaleX, scaleY);
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.scale(scale, scale);
this.printAll(g2);

g2.setTransform(originalTransform);

Note: I haven't actually tested this. 注意:我还没有实际测试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM