Skip to content
Advertisement

How to centre-justify and format String in Java

I know that there are many previous explanations, but similar to my problem I did not find !

Simply i have a code to drow a bill info using graphics2d !

My Full Code IS :

 public PageFormat getPageFormat(PrinterJob pj) {

    PageFormat pf = pj.defaultPage();
    Paper paper = pf.getPaper();

    double middleHeight = 99999;
    double headerHeight = 2.0;
    double footerHeight = 2.0;
    double width = convert_CM_To_PPI(8);      //printer know only point per inch.default value is 72ppi
    double height = convert_CM_To_PPI(headerHeight + middleHeight + footerHeight);
    paper.setSize(width, height);
    paper.setImageableArea(
            0,
            2,
            width,
            height - convert_CM_To_PPI(1)
    );   //define boarder size    after that print area width is about 180 points

    pf.setOrientation(PageFormat.PORTRAIT);           //select orientation portrait or landscape but for this time portrait
    pf.setPaper(paper);

    return pf;
}

protected static double convert_CM_To_PPI(double cm) {
    return toPPI(cm * 0.393600787);
}

protected static double toPPI(double inch) {
    return inch * 72d;
}

public class BillPrintable implements Printable {

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
            throws PrinterException {

        int result = NO_SUCH_PAGE;
        if (pageIndex == 0) {

            Graphics2D g2d = (Graphics2D) graphics;

            double width = pageFormat.getImageableWidth();

            g2d.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());

            FontMetrics metrics = g2d.getFontMetrics(new Font("TimesRoman", Font.BOLD, 7));

            int idLength = metrics.stringWidth("000");
            int amtLength = metrics.stringWidth("000000");
            int qtyLength = metrics.stringWidth("00000");
            int priceLength = metrics.stringWidth("000000");
            int prodLength = (int) width - idLength - amtLength - qtyLength - priceLength - 17;

            int productPosition = 0;
            int discountPosition = prodLength + 5;
            int pricePosition = discountPosition + idLength + 10;
            int qtyPosition = pricePosition + priceLength + 4;
            int amtPosition = qtyPosition + qtyLength;

            try {
                /*Draw Header*/
                int y = 20;
                int yShift = 10;
                int headerRectHeight = 15;
                int headerRectHeighta = 40;

                String itiname;
                String CatToGetID;
                double couniti;
                double iticounter;
                String proptoremove;
                nf.setMaximumFractionDigits(2);

                int v = modelUpper.getRowCount();
                int h = modelUpper.getRowCount();

                String[] strArray = new String[v];
                String[] strCount = new String[v];
                String[] strAmount = new String[v];

                for (int x = 0; x < v; x++) {

                    proptoremove = String.valueOf(modelUpper.getValueAt(x, 3));
                    proptoremove = proptoremove.replace("NOK", "");
                    proptoremove = proptoremove.replace(" ", "");
                    proptoremove = proptoremove.replace(",", "");

                    iticounter = Double.parseDouble(String.valueOf(modelUpper.getValueAt(x, 1)));

                    couniti = Double.valueOf(proptoremove);

                    itiname = String.valueOf(modelUpper.getValueAt(x, 0));

                    strArray[x] = itiname;
                    strCount[x] = Double.toString(iticounter);
                    strAmount[x] = Double.toString(couniti);

                }

                cpuntAll = Double.valueOf(pricetoset);

                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 14));
                g2d.drawString("    -::: " + DashBord.MineName.getText().replace("Restaurant -", "") + " :::-", 16, y);
                y += yShift;
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("", 12, y);
                y += headerRectHeight;
                g2d.drawString("Iteam Name     | Quantity |   Total   ", 10, y);
                y += yShift;
                g2d.drawString("--------------------------------------------------------", 10, y);
                y += headerRectHeight;
                g2d.setFont(new Font("monospaced", Font.BOLD, 10));

                for (int q = 0; q < h; q++) {

                    String ss = String.format("%-3s %7s %10s", strArray[q], arformat.format(Double.valueOf(strCount[q])), arformat.format(Double.valueOf(strAmount[q])) + " NOK");

                    g2d.drawString(ss, 10, y);
                    y += yShift;

                }
                
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("--------------------------------------------------------", 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("monospaced", Font.BOLD, 10));
                g2d.drawString((String.format("%-3s %s", "Totil: ", arformat.format(cpuntAll) + " NOK")), 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("--------------------------------------------------------", 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("monospaced", Font.BOLD, 12));
                g2d.drawString((String.format("%-3s %s", "Invoice Number :", arformat.format(Double.valueOf(InvNum)))), 10, y);
                y += yShift;
                y += yShift;
                g2d.drawString("CashOut By : " + DashBord.NameLogIn.getText(), 10, y);
                y += yShift;
                y += yShift;

                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-M-yyyy hh:mm:ss");
                LocalDateTime now = LocalDateTime.now();

                g2d.drawString("Time And Date : " + dtf.format(now), 10, y);
                y += yShift;
                y += yShift;
                g2d.setFont(new Font("TimesRoman", Font.CENTER_BASELINE, 10));
                g2d.drawString("--------------------------------------------------------", 10, y);

            } catch (NumberFormatException r) {
            }

            result = PAGE_EXISTS;
        }

        return result;
    }

}

the output is like this :

enter image description here

my problim is in this line :

        String ss = String.format("%-3s %7s %10s", strArray[q], arformat.format(Double.valueOf(strCount[q])), arformat.format(Double.valueOf(strAmount[q])) + " NOK");

After i used a String.format it is must do the center of the text so it will be like this !.

To clarify more, I want the Autobot to be as this example :

--------------------------------
|Iteam Name | Quantity | Total |
--------------------------------
|Test            3       15 NOK
|Shawerma        2     27.2 NOK
--------------------------------
Totil: 42.2 NOK
--------------------------------
Invoice Number : 16
CashOut By : IT
Time And Date : 31-3-2021 02:10:20
--------------------------------

Any Help ?

Advertisement

Answer

I would suggest you need to decide what the width of each column should be.

For example:

  1. Item Name – 100
  2. Quantity – 50
  3. Total – 50

Then when you print each row:

  1. The item would be left justified, then you just use 0, for the x value.
  2. The quantity would be right justified. Therefore you calculate the length of the text using the font metrics and then use 150 – text length as the x value.
  3. The total would be right justified so you use the same approach as the quantity except you use 200 – text length for the x value.

I would also suggest that all your total values be formatted to 2 decimal places.

Note you may want to use a monospaced font to make alignment easier.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement