string.format()无法正确处理可打印文件(使用graphics2d)

pcww981p  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(408)

我试图写一些代码,将打印一些数字右对齐,但注意到,当有一个以上的数字,格式变得混乱和抛出一切。我还注意到 Strings 我正在试着打印,但它们也没有正确对齐。
这是我的密码:

public class Printer implements Printable
{
    Object[][] data;
    String lines;

    public Printer(Object[][] data)
    {
        this.data = data;
        lines = convertArrayToString();

        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        Paper paper = new Paper();
        paper.setImageableArea(9, 9, paper.getWidth() - (9 * 2), paper
                .getHeight());
        PrintRequestAttributeSet attributes = 
                new HashPrintRequestAttributeSet();
        attributes.add(OrientationRequested.LANDSCAPE);
        job.setPrintable(this, pf);
        boolean ok = job.printDialog();
        if (ok)
        {
            try
            {
                pf.setOrientation(PageFormat.LANDSCAPE);
                job.print(attributes);
            } catch (PrinterException ex)
            {
                /* The job did not successfully complete */
            }
        }
    }

    @Override
    public int print(Graphics g, PageFormat pf, int page) 
            throws PrinterException {
        if (page > 0)
            return NO_SUCH_PAGE;

        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableY(), pf.getImageableX());
        g.setFont(new Font("ARIAL", Font.PLAIN, 11));
        drawString(g, lines, 10, 10);

        return PAGE_EXISTS;
    }

    private void drawString(Graphics g, String message, int x, int y)
    {
        for (String line : message.split("\n"))
            g.drawString(line, x, y += g.getFontMetrics().getHeight());
    }

    private String convertArrayToString() {
        String line =  "ID |   REVERB |     GAIN |     PRESENCE |     MIDDLE | "
                + "   BASS |           ARTIST NAME |           AMPLIFIER NAME "
                + "|\n" 
                + "------------------------------------------------------------"
                + "------------"
                + "------------------------------------------------------------"
                + "-------------------------\n";

        for (int i = 0; i < data.length; i++)
        {
            String currentLine = "";

            currentLine = String.format(" %2d |              %2d |           "
                    + "%2d |                     %2d |                %2d |"
                    + "           %2d |%30s |%30s |\n", data[i][0], data[i][1], 
                    data[i][2], data[i][3], data[i][4], data[i][5], data[i][6], 
                    data[i][7]);
            line += currentLine;
        }

        return line;
    }  
}

下面是代码打印的内容:

如果有人知道为什么要用 String.format() 方法只适用于有时,任何输入将不胜感激!谢谢您!

2mbi3lxu

2mbi3lxu1#

解决办法是改变 Font 反对 new Font(Font.MONOSPACED, Font.PLAIN, 11) ,如上所述。

相关问题