简体   繁体   English

如何在Java Swing的每个页面中用页脚打印整个JPanel

[英]How to print whole JPanel with a footer in every page in java swing

Ok it may simple. 好吧,这可能很简单。 But can't figure it out. 但是无法弄清楚。

I have a JPanel that contains a JTable. 我有一个包含JTable的JPanel。 JTable contains few rows, Sometime more, because the table model i push into it depends on database. JTable包含几行,有时更多,因为我推送到其中的表模型取决于数据库。

However, i don't use any JScollpane that enclose my JTable. 但是,我不使用任何包含JTable的JScollpane。 As a result, when JTable contains more and more row, parent JPanel automatically resized its height. 结果,当JTable包含越来越多的行时,父级JPanel会自动调整其高度。 That is working fine. 很好

Problem is i want to print whole JPanel at a time. 问题是我想一次打印整个JPanel。 may be it needs several page, i don't care. 可能需要几页,我不在乎。 I can print JTable directly with a header and footer. 我可以直接使用页眉和页脚打印JTable。 But in my case JPanel contains some important component like JLable. 但就我而言,JPanel包含一些重要的组件,例如JLable。 So, there is no other way to avoid printing of JPanel. 因此,没有其他方法可以避免打印JPanel。

I search several online link, everywhere i found a suggestion to implements printable interface. 我搜索了几个在线链接,到处都找到实现可打印界面的建议。

so i implements printable in my class and overload print.... 所以我在我的课上实现了printable并重载了print ....

@Override
public int print(Graphics arg0, PageFormat arg1, int arg2) throws PrinterException {

    Graphics2D g2d = (Graphics2D) arg0;
    g2d.translate((int) arg1.getImageableX(), (int) arg1.getImageableY());

    float pageWidth = (float) arg1.getImageableWidth();
    float pageHeight = (float) arg1.getImageableHeight();

    float imageHeight = (float) paintPanel.getHeight();
    float imageWidth = (float) paintPanel.getWidth();

    float scaleFactor = Math.min((float) pageWidth / (float) imageWidth, (float) pageHeight / (float) imageHeight);

    int scaledWidth = (int) (((float) imageWidth) * scaleFactor);

    int scaledHeight = (int) (((float) imageHeight) * scaleFactor);

    BufferedImage canvas = new BufferedImage(paintPanel.getWidth(), paintPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D gg = canvas.createGraphics();
    paintPanel.paint(gg);
    Image img = canvas;
    g2d.drawImage(img, 0, 0, scaledWidth, scaledHeight, null);
    return Printable.PAGE_EXISTS;
}

Its not working. 它不起作用。

Another problem that is my second problem. 另一个问题是我的第二个问题。 I want to place a footer JPanel in every page. 我想在每个页面中放置一个页脚JPanel。 So how could it possible. 那么怎么可能。

Help me please. 请帮帮我。 Thanks. 谢谢。

So based on this example which demonstrates how to print a component across multiple pages, I modified it to allow for the printing of a footer. 因此,基于演示如何在多个页面上打印组件的示例 ,我对其进行了修改以允许打印页脚。

This example draws directly via the Graphics context, but conceptually, the process would be simple enough to paint using a supplied JComponent of some sort. 该示例直接通过Graphics上下文进行绘制,但是从概念上讲,该过程将非常简单,可以使用提供的某种JComponent进行绘制。

PageExample

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.PrinterResolution;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class PrintMe {

    public static void main(String[] args) {
        new PrintMe();
    }

    public PrintMe() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                TestPane testPane = new TestPane();

                JButton btn = new JButton("Print");
                btn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                        aset.add(MediaSizeName.ISO_A4);
                        aset.add(new PrinterResolution(300, 300, PrinterResolution.DPI));

                        PrinterJob pj = PrinterJob.getPrinterJob();
                        pj.setPrintable(new MultiPagePrintable(testPane));

                        if (pj.printDialog(aset)) {
                            try {
                                pj.print(aset);
                                testPane.getParent().invalidate();
                                testPane.getParent().validate();
                            } catch (PrinterException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(testPane));
                frame.add(btn, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel implements Scrollable {

        private BufferedImage img;

        public TestPane() {
            try {
                img = ImageIO.read(some image source);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x = (getWidth() - img.getWidth()) / 2;
                int y = (getHeight() - img.getHeight()) / 2;
                g2d.drawImage(img, x, y, this);
                g2d.dispose();
            }
        }

        @Override
        public Dimension getPreferredScrollableViewportSize() {
            return new Dimension(200, 200);
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 128;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 128;
        }

        @Override
        public boolean getScrollableTracksViewportWidth() {
            return false;
        }

        @Override
        public boolean getScrollableTracksViewportHeight() {
            return false;
        }

    }

    public class MultiPagePrintable implements Printable {

        private JComponent component;
        private int lastPage = 0;
        private double yOffset;

        private Font footerFont;

        public MultiPagePrintable(JComponent component) {
            this.component = component;

            footerFont = new Font("Arial", Font.BOLD, 24);
        }

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            int result = NO_SUCH_PAGE;

            String name = "I be mighty!";
            String page = Integer.toString(pageIndex);

            FontMetrics fm = graphics.getFontMetrics(footerFont);
            double footerHeight = fm.getHeight() + 4;

            double height = pageFormat.getImageableHeight() - footerHeight;
            component.setSize(component.getPreferredSize());

            if (lastPage != pageIndex) {
                lastPage = pageIndex;
                yOffset = height * pageIndex;
                if (yOffset > component.getHeight()) {
                    yOffset = -1;
                }
            }

            if (yOffset >= 0) {
                Graphics2D g2d = (Graphics2D) graphics.create();

                g2d.translate((int) pageFormat.getImageableX(),
                                (int) pageFormat.getImageableY());

                g2d.translate(0, -yOffset);
                component.printAll(g2d);
                g2d.translate(0, +yOffset);
                Shape footerArea = new Rectangle2D.Double(0, height, pageFormat.getImageableWidth(), footerHeight);
                g2d.setColor(Color.WHITE);
                g2d.fill(footerArea);
                g2d.setColor(Color.RED);
                g2d.draw(footerArea);

                g2d.setColor(Color.BLACK);


                g2d.translate(0, (pageFormat.getImageableHeight() - footerHeight));
                float x = 2;
                float y = (float)((footerHeight - fm.getHeight()) / 2d);
                g2d.drawString(name, x, y + fm.getAscent());

                x = (float)(pageFormat.getImageableWidth() - fm.stringWidth(page) - 2);
                g2d.drawString(page, x, y + fm.getAscent());

                g2d.dispose();
                result = PAGE_EXISTS;
            }
            return result;
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM