Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中居中对齐和格式化字符串_Java_String - Fatal编程技术网

如何在Java中居中对齐和格式化字符串

如何在Java中居中对齐和格式化字符串,java,string,Java,String,我知道之前有很多解释,但类似我的问题我没有发现 简单地说,我有一个代码,可以使用graphics2d显示账单信息 我的全部代码是: public PageFormat getPageFormat(PrinterJob pj) { PageFormat pf = pj.defaultPage(); Paper paper = pf.getPaper(); double middleHeight = 99999; double headerHeight = 2.

我知道之前有很多解释,但类似我的问题我没有发现

简单地说,我有一个代码,可以使用graphics2d显示账单信息

我的全部代码是:

 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;
    }

}
在我使用了
String.format
之后,它必须位于文本的中心,这样它就会像这样

为了进一步澄清,我想让汽车人成为以下示例:

--------------------------------
|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
--------------------------------

有什么帮助吗?

%-3s
表示要为配料保留3个字符宽度。很明显,你的配料比那要长得多。String.format处理的值太长,仅。。将它们打印出来,这意味着所有其他项目都会向右移动


解决方案很简单:更新
%Xs
,使X至少与最长配料一样大。

%-3s
表示要为配料保留3个字符宽度。很明显,你的配料比那要长得多。String.format处理的值太长,仅。。将它们打印出来,这意味着所有其他项目都会向右移动


解决方案很简单:更新
%Xs
,使X至少与最长配料一样大。

我建议您需要决定每列的宽度

例如:

  • 项目名称-100
  • 数量-50
  • 总数-50
  • 然后打印每行时:

  • 将左对齐,然后您只需使用0作为x值
  • 数量
    是正确的。因此,您可以使用字体度量计算文本长度,然后使用150-text length作为x值
  • 总计
    将右对齐,因此您使用与数量相同的方法,除了使用200-文本长度作为x值
  • 我还建议将所有的总值格式化为小数点后2位


    注意:您可能需要使用单间距字体,以便更容易对齐。

    我建议您需要确定每列的宽度

    例如:

  • 项目名称-100
  • 数量-50
  • 总数-50
  • 然后打印每行时:

  • 将左对齐,然后您只需使用0作为x值
  • 数量
    是正确的。因此,您可以使用字体度量计算文本长度,然后使用150-text length作为x值
  • 总计
    将右对齐,因此您使用与数量相同的方法,除了使用200-文本长度作为x值
  • 我还建议将所有的总值格式化为小数点后2位


    注意:您可能希望使用单间距字体,以便更容易对齐。

    您根本不希望这样。您希望“总计”数字在小数点处对齐,并且希望总计值在“总计”列下对齐。您希望“Quantity”数字正确对齐,因此“Quantity”(和“Total”)标题也应该正确对齐。“Item Name”标题应该像其列内容一样左对齐。我在这里看不到任何应该居中对齐的内容。@user207421如果我理解正确的话。。。你能给我举个例子或者编辑我的代码来做这个吗?因为我不知道怎么按照你的解释去做!我只是引用一般原则。数字应该是右对齐的,除非它们有小数点,否则它们应该是小数点对齐的。总数应该与它们的总数对齐。标题应与其标题栏的内容对齐。以几乎所有的信用卡收据为例。我在1976年学的,你根本不想学。您希望“总计”数字在小数点处对齐,并且希望总计值在“总计”列下对齐。您希望“Quantity”数字正确对齐,因此“Quantity”(和“Total”)标题也应该正确对齐。“Item Name”标题应该像其列内容一样左对齐。我在这里看不到任何应该居中对齐的内容。@user207421如果我理解正确的话。。。你能给我举个例子或者编辑我的代码来做这个吗?因为我不知道怎么按照你的解释去做!我只是引用一般原则。数字应该是右对齐的,除非它们有小数点,否则它们应该是小数点对齐的。总数应该与它们的总数对齐。标题应与其标题栏的内容对齐。以几乎所有的信用卡收据为例。我在1976年学会了这些东西。谢谢你的建议,我已经在使用这种字体(单行距),但是你能解释给我或者修改代码,以便按照你的建议去做吗?我确实解释了该怎么做。您需要编写3个字符串,而不是尝试为标题和循环中的每个项目编写单个字符串。您需要按照我的建议为3个字符串中的每一个计算“x”值。问题已经解决,谢谢!谢谢你的建议,我已经在使用这种字体(单行距),但是你能给我解释一下或者修改代码,以便按照你的建议去做吗?我确实解释了该怎么做。您需要编写3个字符串,而不是尝试为标题和循环中的每个项目编写单个字符串。您需要按照我的建议为3个字符串中的每一个计算“x”值。问题已经解决,谢谢!
    --------------------------------
    |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
    --------------------------------