1
我正在嘗試打印可打印組件(發票文檔)。我使用JComponent
而不是JPanel
,因爲我不想要背景。該組件有許多子組件。我的可打印Swing組件的所有部分都不打印
主要組件實現Printable並具有print
-方法,該方法調用printAll(g)
以便所有子組件都應該打印。但是我的子組件不打印。
我錯過了什麼?所有子組件是否也必須實現Printable?
在我的代碼下面,TopHeader未打印。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class PPanel extends JComponent implements Printable {
static double w;
static double h;
public PPanel() {
this.setLayout(new BorderLayout());
this.add(new JLabel("Document Body"), BorderLayout.CENTER);
this.add(new TopHeader(), BorderLayout.NORTH);
}
class TopHeader extends JComponent {
public TopHeader() {
this.setLayout(new BorderLayout());
JLabel companyName = new JLabel("Company name");
JLabel docType = new JLabel("Document type");
this.add(companyName, BorderLayout.WEST);
this.add(docType, BorderLayout.EAST);
}
}
public static void main(String[] args) {
final PPanel p = new PPanel();
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(p);
try {
job.print();
} catch (PrinterException ex) {
// print failed
}
// Preview
new JFrame() {{ getContentPane().add(p); this.setSize((int)w, (int)h); setVisible(true); }};
}
@Override
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());
w = pf.getImageableWidth();
h = pf.getHeight();
this.setSize((int)w, (int)h);
this.setPreferredSize(new Dimension((int)w, (int)h));
this.doLayout();
this.printAll(g);
return PAGE_EXISTS;
}
}
謝謝,但我不明白我可以如何使用I.e.在我的例子中,如果我使用JTextField而不是JLabel,則使用'javax.swing.text.JTextComponent.print()'。當我執行'printAll(g)'時,不是調用'print()'方法嗎?或者我必須爲此編寫任何特定的代碼? – Jonas 2010-05-20 15:52:16
這取決於您是要打印屏幕上顯示的內容還是「JTextComponent」中可能太大而無法滾動的內容。 – trashgod 2010-05-20 17:38:10