我正在尝试使用 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;
}
}
}