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

时间:2013-09-11 06:47:34

标签: java swing

我正在尝试使用java.awt.print打印JPanel。我想打印出一个JPanel。我尝试了下面的代码,它只包含一个按钮。当打印出来时,它出现在页面的左下角,但我需要将它打印在屏幕上显示的原始位置。是否有设置边界以确定位置的方法?

在这里输入代码

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;
        }

    }
}

1 个答案:

答案 0 :(得分:3)

print方法中,您只打印按钮:

ok.printAll(g2);

要打印JPanel,您应该调用该JPanel的printAll方法:

this.printAll(g2);

如果您想确保面板适合页面,您需要根据在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);

注意:我实际上没有测试过这个。