我正在尝试创建一个Java类,其中包含JLabel的JFrame将打印在完整的A5页面上(JFrame设置为A5页面的大小)
为了做到这一点,我已经使用了这个类
这个我写过的课
public class test2 extends PrintUIWindow {
public test2(JFrame f) {
super(f);
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args)
{
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f=new JFrame ("hello");
f.setLayout(null);
f.setSize(420,595);
JLabel test=new JLabel ("issuer");
f.add(test);
test.setBounds(new Rectangle(new Point(310, 50), test.getPreferredSize()));
f.setBackground(Color.white);
f.setVisible(true);
PrintUIWindow p=new PrintUIWindow (f);
p.actionPerformed(null);
}
}
问题是,不是将整个JFrame打印到页面上,而是仅打印其中的一部分,其余部分不在页面边框
什么可以解决这个问题?
答案 0 :(得分:0)
查看this
我也发现了这个:
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;
}
}
要使用Printer类打印帧,请尝试:
JFrame yourComponent = new JFrame();
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.LANDSCAPE);
PageFormat postformat = pjob.pageDialog(preformat);
if (preformat != postformat) {
pjob.setPrintable(new Printer(yourComponent), postformat);
if (pjob.printDialog()) {
pjob.print();
}
}