gpt4 book ai didi

java - 如何在多页中打印一个大的 JPanel

转载 作者:行者123 更新时间:2023-12-02 05:27:00 24 4
gpt4 key购买 nike

我想打印一个非常大的面板,这个面板包含一些组件,如 jtable、jlabel 和其他 jpanel。现在我想将其打印在不同的页面中。但我不知道该怎么做。我已经在我的面板类中实现了 Printable 。但如果我打印它,我只会得到一页。

最佳答案

试试这个?

package com.mymoney.util;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Pageable;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.RepaintManager;

public class PrintUtil implements Printable, Pageable {
private Component componentToBePrinted;
private PageFormat format;
private int numPages;

public PrintUtil(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
Dimension page = this.componentToBePrinted.getPreferredSize();
numPages = (int) Math.ceil(page.height/format.getImageableY());
}

public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
printJob.setPageable(this);
format = printJob.defaultPage();

if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}

public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if ((pageIndex < 0) | (pageIndex >= numPages)) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()- pageIndex*componentToBePrinted.getPreferredSize().height);
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}

public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}

public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}

@Override
public int getNumberOfPages() {
// TODO Auto-generated method stub
return numPages;
}

@Override
public PageFormat getPageFormat(int arg0) throws IndexOutOfBoundsException {
return format;
}

@Override
public Printable getPrintable(int arg0) throws IndexOutOfBoundsException {
// TODO Auto-generated method stub
return this;
}
}

引用 --> https://community.oracle.com/thread/1263759?start=0&tstart=0

关于java - 如何在多页中打印一个大的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25919083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com