在java中仅打印标签(而不是整个框架)
检查下面的图片 条形码作为标签添加。单击“打印”后,我只需要打印条形码。我该如何打印条形码。我看到了一些示例,但它们打印了整个框架,即包括框架上的“打印”按钮 更新 现在我将打印到左上角。如何将其定位到我想要的任何位置在java中仅打印标签(而不是整个框架),java,swing,printing,jframe,actionlistener,Java,Swing,Printing,Jframe,Actionlistener,检查下面的图片 条形码作为标签添加。单击“打印”后,我只需要打印条形码。我该如何打印条形码。我看到了一些示例,但它们打印了整个框架,即包括框架上的“打印”按钮 更新 现在我将打印到左上角。如何将其定位到我想要的任何位置 需要做的只是为单个组件实现可打印的 下面是一个基本的实现示例,可以对该主题有所帮助: /** * Allows for printing a single UI component. * @author Ben Barkay */ public class Compone
需要做的只是为单个
组件实现可打印的
下面是一个基本的实现示例,可以对该主题有所帮助:
/**
* 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);
}
}
条形码图像在哪里?您可以采取一种简单的方法,打印条形码图像而不是标签。它存储在我的驱动器中,我检索它以显示给用户,然后要求按图像中所示进行打印。确定后,您只需执行以下代码:Desktop.getDesktop().print(新文件(路径/to/image))
使用类,还需要一个try catch
块别忘了。谢谢它工作了。但是我在左上角得到了打印。如何定位到屏幕的中心或任何位置。将图像放在update@user2958963在组件打印机#打印(图形、页面格式、int)
,您可以将Graphics
转换为Graphics2D
并使用Graphics2D#translate(int,int)
来移动它。就在组件绘制(图形)之前代码>,发布<代码>((Graphics2D)图形)。翻译(addToX,addToY)
其中addToX
是向右移动的像素量,addToY
是向下移动的像素量。我知道了。再次感谢