1

下の画像を確認してください

ここに画像の説明を入力

バーコードがラベルとして追加されます。[印刷] をクリックしたら、バーコードだけを印刷する必要があります。

更新 今、印刷物を左上隅に配置しています。必要な場所に配置する方法

ここに画像の説明を入力

4

1 に答える 1

3

行う必要があるのはPrintable、単一のComponent.

これは、主題に光を当てることができる基本的な実装例です。

/**
 * 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);
    }
}
于 2013-11-14T07:09:33.150 に答える