当我按Shift+F6
执行我的程序时,它会很好地打印条形码,但是当我通过执行以下操作创建jar文件时
Shift+F11
当我在终端
中执行时,它会在dist下创建jar文件java -jar BarcodePrintTest.jar
显示错误,如
错误:无法访问jarfile BarcodePrintTest.jar
以下是我的代码
import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.BarcodeException;
import net.sourceforge.barbecue.output.OutputException;
import javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.*;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.awt.print.PrinterException;
import java.awt.print.Printable;
import java.io.File;
import net.sourceforge.barbecue.BarcodeImageHandler;
public class BarcodePrintTest implements Printable {
public static void main (String[] args) {
BarcodePrintTest barCodePrinter = new BarcodePrintTest();
barCodePrinter.execute();
}
private void execute() {
try {
PageFormat pFormat = new PageFormat();
//pFormat.setOrientation(PageFormat.LANDSCAPE);
PrinterJob pJob = PrinterJob.getPrinterJob();
pJob.setPrintable(this, pFormat);
//PrintServiceAttribute printerName = new PrinterName("Zebra LP2824", null);
PrintServiceAttribute printerName = new PrinterName("Zebra-TLP2844", null);
AttributeSet attr = new HashPrintServiceAttributeSet(printerName);
PrintService[] printServiceArray = PrintServiceLookup.lookupPrintServices(null, attr);
PrintService printService = printServiceArray[0];
pJob.setPrintService(printService);
pJob.print();
} catch (PrinterException e) {
System.err.println("Error occurred in execute");
}
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
//adjust the following variables for positioning and size of barcode printout
double scale = 0.57;
int barHeight = 50;
int barWidth = 1;
int x = 140;
int y = 0;
Graphics2D g2 = (Graphics2D) graphics;
g2.translate((int)(pageFormat.getImageableX()), (int)(pageFormat.getImageableY()));
g2.scale(scale, scale);
if (pageIndex == 0) {
Barcode barcode = null;
try {
String barcodedata="100001017SRM12345678";
barcode = BarcodeFactory.createCode128(barcodedata);
} catch (BarcodeException e) {
e.printStackTrace();
}
try {
barcode.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
barcode.setDrawingText(true);
barcode.setDrawingQuietSection(true);
barcode.setResolution(96);
barcode.setBarHeight(barHeight);
barcode.setBarWidth(barWidth);
barcode.draw(g2, x, y);
} catch (OutputException e) {
e.printStackTrace();
}
return Printable.PAGE_EXISTS;
} else {
return Printable.NO_SUCH_PAGE;
}
}
}