打印多个 JPanel [英] Printing a number of JPanels

查看:37
本文介绍了打印多个 JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习使用 Java Swing 进行打印,所以如果这个问题很幼稚,请耐心等待.

I'm just starting to learn about printing with Java Swing, so please bear with me if this question is very naive.

我有一个相当复杂的布局,其中包含多个包含 JLabel 的其他 JPanel 的 JPanel.我想以某种方式在打印机上很好地打印出来.

I have a rather complex layout with multiple JPanels that contain other JPanels that contain JLabels. I want somehow to print this nicely on a printer.

我知道我可以在代表打印页面的 Graphics2D 对象上绘画",但这需要我单独定位每个对象.我希望能够使用 Swing 布局管理器来布局我页面上的项目.一种方法是调用 jp.paint(g2d),其中 jp 是一个 JPanel,g2d 是表示打印页面的 Graphics2D 对象.但是,据我所知,这只会打印在屏幕上实际可见的 JPanel.如果 JPanel 不可见,则不会打印.

I know that I can "paint" on a Graphics2D object that represents a printed page, but that requires me to position each object individually. I would like to be able to use the Swing layout managers to layout the items on my page. One way to do this is to call jp.paint(g2d), where jp is a JPanel and g2d is the Graphics2D object representing the printed page. However, as far as I can see, this will only print a JPanel that is actually visible on the screen. If the JPanel is not visible, it will not be printed.

那么有没有什么办法可以在不首先在计算机屏幕上显示 JPanel 的情况下布局一个(相当复杂的)JPanel 并将其发送到打印机?

So is there any way to layout a (rather complex) JPanel and send it to a printer without first displaying the JPanel on the computer screen?

还是我在这里完全走错了路?

Or am I on a totally wrong track here?

推荐答案

如何在不可见的情况下打印 JPanel 的精简示例.

Stripped down example of how to print a JPanel while invisible.

public class TestPrinterSmall  {
static class JPanelPrintable extends JPanel implements Printable {
    public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
        if (page > 0) return Printable.NO_SUCH_PAGE;
        printAll(g);  
        return Printable.PAGE_EXISTS;
    }
};
private static void printIt(Printable p) throws PrinterException {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(p);
    if (job.printDialog()) job.print();
}    
public static void main(String args[]) throws PrinterException {
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.setSize(400,400);
    final JPanelPrintable j = new JPanelPrintable(); 
    j.setLayout(new BorderLayout());
    j.add(new JButton("1111"),BorderLayout.NORTH);
    j.add(new JButton("2222"),BorderLayout.SOUTH);            
    f.add(j);f.repaint();f.pack();
    //f.setVisible(true);
    printIt(j);
}
}

输出:

(nothing)

打印机:

这篇关于打印多个 JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆