通过自定义Printable类进行JTable打印

时间:2015-02-04 12:23:54

标签: java swing printing jtable

我有一个JTable用于捕获用户输入,稍后将在点击“打印”按钮时打印。我有一个图像,我想成为标题,另一个图像是一个页脚。显示这一点的图像可以找到here。我按照oracle documents here中找到的示例进行了操作。我希望它完全按照TablePrintdemo3 here中的方式完成。

请允许我在这里发布课程。 这是我的第一堂课:

public class Product {
String productDescription;
Double productPrice;
//dummy properties
Integer productQuantity;
Double productTotalAmount;

 public Product() {
    this.productDescription = "";
    this.productPrice = 0.0;
    this.productTotalAmount = 0.0;
    this.productQuantity = 0;

 }//getters and setters here
  }

第二类是自定义模型,如下所示:

public class ProductTableModel extends AbstractTableModel {

private final List<String> columnNames;
private final List<Product> products;

public ProductTableModel() {
    String[] header = new String[] {
        "Quantity",
        "Description",
        "Unity Price",
        "Total Price"
    };
    this.columnNames = Arrays.asList(header);
    this.products = new ArrayList<>();
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    switch (columnIndex) {
        case 0: return Integer.class;
        case 1: return String.class;
        case 2: return Double.class;
        case 3: return Double.class;
            default: throw new ArrayIndexOutOfBoundsException(columnIndex);
    }
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Product product = this.getProduct(rowIndex);
    switch (columnIndex) {
        case 0: return product.getProductQuantity();
        case 1: return product.getProductDescription();
        case 2: return product.getProductPrice();
        case 3: return product.getProductTotalAmount();
            default: throw new ArrayIndexOutOfBoundsException(columnIndex);
    }
}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
}

@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    if (columnIndex < 0 || columnIndex >= getColumnCount()) {
        throw new ArrayIndexOutOfBoundsException(columnIndex);
    } else {
        Product product = this.getProduct(rowIndex);
        switch (columnIndex) {
            case 0: product.setProductQuantity((Integer)aValue); break;
            case 1: product.setProductDescription((String)aValue); break;
            case 2: product.setProductPrice((Double)aValue); break;
            case 3: product.setProductTotalAmount((Double)aValue); break;
        }
        fireTableCellUpdated(rowIndex, columnIndex);
    }
}

@Override
public int getRowCount() {
    return this.products.size();
}

@Override
public int getColumnCount() {
    return this.columnNames.size();
}

@Override
public String getColumnName(int columnIndex) {
    return this.columnNames.get(columnIndex);
}

public void setColumnNames(List<String> columnNames) {
    if (columnNames != null) {
        this.columnNames.clear();
        this.columnNames.addAll(columnNames);
        fireTableStructureChanged();
    }
}

public List<String> getColumnNames() {
    return Collections.unmodifiableList(this.columnNames);
}

public void addProducts(Product product) {
    int rowIndex = this.products.size();
    this.products.add(product);
    fireTableRowsInserted(rowIndex, rowIndex);
}

public void addProducts(List<Product> productList) {
    if (!productList.isEmpty()) {
        int firstRow = this.products.size();
        this.products.addAll(productList);
        int lastRow = this.products.size() - 1;
        fireTableRowsInserted(firstRow, lastRow);
    }
}
 public void addEmptyRow(){
 products.add(new Product());
 this.fireTableRowsInserted(products.size()-1, products.size()-1);
 }
public void insertProduct(Product product, int rowIndex) {
    this.products.add(rowIndex, product);
    fireTableRowsInserted(rowIndex, rowIndex);
}

public void deleteProduct(int rowIndex) {
    if (this.products.remove(this.products.get(rowIndex))) {
        fireTableRowsDeleted(rowIndex, rowIndex);
    }
}

public Product getProduct(int rowIndex) {
    return this.products.get(rowIndex);
}

public List<Product> getProducts() {
    return Collections.unmodifiableList(this.products);
}

public void clearTableModelData() {
    if (!this.products.isEmpty()) {
        int lastRow = products.size() - 1;
        this.products.clear();
        fireTableRowsDeleted(0, lastRow);
    }
  }
}

第三课是我的如下:

      public class NiceTablePrinting extends MainClass{

       @Override
       protected JTable initializeTable(TableModel model) {
       return new NicePrintingJTable(model);
        }



private static class NicePrintingJTable extends JTable {

    public NicePrintingJTable(TableModel model) {
        super(model);
        }

    /**
     * Overridden to return a fancier printable, that wraps the default.
     * Ignores the given header and footer. Renders its own header.Always
     * uses the page number as the footer.
     */
    @Override
    public Printable getPrintable(PrintMode printMode,
            MessageFormat headerFormat,
            MessageFormat footerFormat) {

        MessageFormat pageNumber = new MessageFormat("- {0} -");

        /* Fetch the default printable */
        Printable delegate = per.getPrintable(printMode,null,pageNumber);

        /* Return a fancy printable that wraps the default */
        return new NicePrintable(delegate);
        }
       }

     private static class NicePrintable implements Printable {

        Printable delegate; 
        //
        BufferedImage header;
        BufferedImage footer;
        //
        boolean imagesLoaded;

        {
        try{

        header=ImageIO.read(getClass().getResource("images/header.PNG"));
        footer=ImageIO.read(getClass().getResource("images/footer.PNG"));
        imagesLoaded=true;
        }
        catch(IOException ex)
        {

        ex.printStackTrace();
        }
        imagesLoaded=false;
        }

       public NicePrintable(Printable delegate) {
        this.delegate = delegate;
         }

    @Override
    public int      print(Graphicsg,PageFormatpf,intpi)throwsPrinterException   

{

        if(!imagesLoaded){
        return delegate.print(g, pf, pi);
        }

        //top origin
        int x=(int)pf.getImageableX();
        int y=(int)pf.getImageableY();
        //
        int iw=(int)pf.getImageableWidth();
        int ih=(int)pf.getImageableHeight();
        //image header
        int hh= header.getHeight();
        int hw=header.getWidth();
        //image footer
        int fh=footer.getHeight();
        int fw=footer.getWidth();
        int fY=ih-fh-10;
        int fX=x;

        //calculating the area to print the table
        int tableX=10;
        int tableY=hh +10;
        int tableW=iw-20;
        int tableH=ih-hh-10-fh-10;

        /* create a new page format representing the shrunken area to print the table into */
        PageFormat format = new PageFormat() {
            @Override
            public double getImageableX() {return tableX;}
            @Override
            public double getImageableY() {return tableY;}
            @Override
            public double getImageableWidth() {return tableW;}
            @Override
            public double getImageableHeight() {return tableH;}
        };

                    /*
         * We'll use a copy of the graphics to print the table to. This protects
         * us against changes that the delegate printable could make to the graphics
         * object.
         */
        Graphics gCopy = g.create();

        /* print the table into the shrunken area */
        int retVal = delegate.print(gCopy, format, pi);

        /* if there's no pages left, return */
        if (retVal == NO_SUCH_PAGE) {
            return retVal;
        }

        /* dispose of the graphics copy */
        gCopy.dispose();

        //draw the images

        g.drawImage(header, x, y, hw, hh, null);
        g.drawImage(footer, fX, fY, fw, fh, null);

        return Printable.PAGE_EXISTS;

    }
}
}

第四节如下:

     public class MainClass {

     private JTable table;
     JFrame frame;
     JButton print;
     JScrollPane sp;
     ProductTableModel model;



    public MainClass(){
    frame= new JFrame("Test Printing");
    frame.setLayout(new java.awt.BorderLayout());
    frame.setVisible(true);
     ///create table
    model=new ProductTableModel();
    table=this.initializeTable(model);
    model.addEmptyRow();

 table.setPreferredScrollableViewportSize(newjava.awt.Dimension(300,300));
    sp= new javax.swing.JScrollPane(table);
    frame.add(sp);
   //button
   print= new JButton("Print");
   frame.add(print,BorderLayout.SOUTH);
   frame.pack();

    print.addActionListener((ActionEvent e) -> {
    try {
        printTable();
    } catch (PrinterException ex) {
         Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE,      null, ex);
    }
        });

       }

    protected JTable initializeTable(TableModel model) {
    return new JTable(model);
        }

     public void printTable() throws PrinterException {
     table.print(JTable.PrintMode.NORMAL, null, null, true, null, true);
    }
    public static void main(String [] args){

       MainClass cl= new MainClass();
     }
   }

我希望按照TablePrintdemo3中的方式设置我的东西。现在我看不出我哪里出错了。请协助。 问题是它只打印表格 - 没有页眉和页脚图像。

0 个答案:

没有答案