简体   繁体   中英

Java Formatter receipt printing issue

I am designing a receipt to print out in Java using the PrinterJob class.

I need some advice.

Based on the example I saw here.

http://www.javadocexamples.com/java_source/__/re/Receipt.java.html

How do I store the output given in the example above in a jTextPanel? I will then print out the text content inside the jTextPanel using the PrinterJob class.

I want to get the following output when I print out the text content inside the jTextPanel from my POS printer.

在此处输入图片说明

Below are the codes I have so far.

String s = String.format("Item Qty Price", "%-15s %5s %10s\n");
        String s1 = String.format("---- --- -----","%-15s %5s %10s\n");
        String output = s + s1;

        jTextPane1.setText(output);

        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat pageFormat = printerJob.defaultPage();
        Paper paper = new Paper();
        paper.setSize(180.0, (double) (paper.getHeight() + lines * 10.0));
        paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight() - margin * 2);
        pageFormat.setPaper(paper);
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        printerJob.setPrintable(jTextPane1.getPrintable(null, null), pageFormat);
        printerJob.print();

Any advice on how can I proceed?

The order in which you pass arguments to String.format is wrong. The format string goes first (the one with the percentage signs), and then you pass multiple arguments, one argument for each percent in the format string.

So in your case:

String s = String.format("%-15s %5s %10s\n", "Item", "Qty", "Price");
String s1 = String.format("%-15s %5s %10s\n", "----", "---", "-----");

You also need a format string for the line items. From your output, that could be:

"%-15s %5d %10.2f\n"

(Which you would use as:

String line = String.format("%-15s %5d %10.2f\n", itemName, quantity, price);

)

If you want to truncate your itemName if it's longer than 15 characters, you can use:

// "%.15s %5d %10.2f\n"
String line = String.format("%.15s %5d %10.2f\n", itemName, quantity, price);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM