首页 > 解决方案 > String.format() 无法与 Printable 一起正常工作(使用 Graphics2D)

问题描述

我正在尝试编写一些代码来打印一些右对齐的数字,但注意到当有多个数字时,格式会变得混乱并把所有东西都扔掉。我还注意到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()方法有时只有效,任何输入将不胜感激!谢谢!

标签: javauser-interfaceprinting

解决方案


解决方法是将Font对象更改为new Font(Font.MONOSPACED, Font.PLAIN, 11),如 VGR 上面建议的那样。


推荐阅读