java - 仅打印(不是整个框架)java swings中的标签

标签 java swing printing jframe actionlistener

检查下图

enter image description here

条形码作为标签添加。单击“打印”后,我只需要打印条形码。我怎么想呢。我看到几个例子,但它们打印了整个框架,即包括打印按钮框架。

更新 现在我将打印件打印到左上角。如何将其放置在我想要的位置

enter image description here

最佳答案

需要做的只是为单个 Component 实现 Printable

这是一个基本的实现示例,可以阐明该主题:

/**
 * Allows for printing a single UI component.
 * @author Ben Barkay
 */
public class ComponentPrinter implements Printable {
    /**
     * The component to be printed.
     */
    Component component;

    /**
     * The amount of pixels to shift the component to the right.
     */
    int translateX;

    /**
     * The amount of pixels to shift the component to the bottom.
     */
    int translateY;

    /**
     * Constructs a new <code>ComponentPrinter</code> for the specified component.
     * @param component     The component that this component printer will print.
     * @param translateX    The amount of pixels to move the component towards the right.
     * @param translateY    The amount of pixels to move the component towards the bottom.
     */
    public ComponentPrinter(Component component, int translateX, int translateY) {
        this.component = component;
        this.translateX = translateX;
        this.translateY = translateY;
    }

    /**
     * Prints the component of this <code>ComponentPrinter</code>.
     * {@inheritDoc}
     */
    @Override
    public int print(Graphics graphics, PageFormat format, int pageIndex)
            throws PrinterException {
        // We assume that there is only one page.
        if (pageIndex == 0) {
            // Position the component appropriately
            ((Graphics2D)graphics).translate(translateX, translateY);

            // Paints the component on the graphics that are about to be printed for this page.
            component.paint(graphics);
            return PAGE_EXISTS;
        }

        // We don't have a page other than the first page.
        return NO_SUCH_PAGE;
    }
}

它的用法是这样的:

JLabel yourJLabelHere = null;
int moveToTheRight = 100;
int moveToTheBottom = 50;
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(new ComponentPrinter(yourJLabelHere, moveToTheRight, moveToTheBottom));
if (printJob.printDialog()) {
    try { 
        printJob.print();
    } catch(PrinterException pe) {
        System.out.println("Error printing: " + pe);
    }
}

关于java - 仅打印(不是整个框架)java swings中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971465/

相关文章:

java - Java 静态数组的排序、平均和查找最小数

java - Swing - JList 内容在动态更新时随机消失

javascript - 如何从 javascript 设置打印份数

javascript - 使用 Javascript 打印(部分)网页

java - Java多个文件和文件夹层次结构

Java 反射 : making a subclass instance be referred to as if it was super instance

java - 我可以在我的 J2EE 应用程序中使用 swing worker 吗?

java - 混合使用 JavaFX 和 Swing

java - 使用 java swing 在彼此之上显示两个对话框

windows - 从命令行以编程方式打印多份副本