Aligning messageformat on printing a JTable

前端 未结 2 809
清歌不尽
清歌不尽 2020-12-12 04:18

I\'m using this for the moment to print out my table, and it works. But I\'m not really happy with the layout of the messageformatting, I would like to have both pagenumber

2条回答
  •  天命终不由人
    2020-12-12 05:04

    You might look at this CustomTablePrintable. You feed it your table's unadorned getPrintable() result. In your PrinterJob, the custom print() will image the table and then draw your footer in the same graphics context. You can use the context's boundary, getFontMetrics() and stringWidth() to determine where to draw your formatted strings.

    Addendum: Here's an example of printing a gray date in the bottom right corner of each page:

    public int print(Graphics g, PageFormat pf, int index) throws PrinterException {
        if (index > 0) return NO_SUCH_PAGE;
        String s = new Date().toString();
        Graphics2D g2d = (Graphics2D) g;
        table.getPrintable(
            JTable.PrintMode.NORMAL, null, null).print(g2d, pf, index);
        Rectangle r = g2d.getClipBounds();
        int dw = g2d.getFontMetrics().stringWidth(s);
        int dh = g2d.getFontMetrics().getHeight();
        System.out.println(index + " " + r);
        g2d.setPaint(Color.gray);
        g2d.drawString(s, r.x + r.width - dw, r.y + r.height - dh);
        return Printable.PAGE_EXISTS;
    }
    

    Addendum: While this approach works for a table that fits on a single page, this article describes printing Components Larger Than One Page.

提交回复
热议问题