如何打印JTable?

时间:2012-10-16 06:39:16

标签: database swing jtable

我有一个显示在JTable中的整个数据库,我添加了一个打印按钮,但它的作用是将JTable中的数据转换为.csv文件,命令excel打开它,用户可以打印它,但它看起来很丑陋。有没有办法将JTable组件发送到打印机?

2 个答案:

答案 0 :(得分:1)

JTable下有一个名为print()的方法。会救你很多。见下文: -

package com.tanyasis.librarymanager;

import java.awt.HeadlessException;
import java.awt.print.PrinterException;
import java.text.MessageFormat;

import javax.swing.JTable;

/**
 * Used to provide printing information and adding information that might be
 * important in a page such as page header, contents and footer. This class
 * makes sure that all contents of a table fit in the given page.
 * 
 * @author Tanyasis Mwanik
 * 
 */
public class PrintTable {

    private JTable table;
    private MessageFormat headerFormat, footerFormat;

    /**
     * Prints the table and provide post printing information to the user if it
     * was succesful
     * 
     * @param table
     *            <code>JTable</code> to be printed
     * @param tableTitle
     *            <code>String</code> to be used as the table header/title
     */
    public PrintTable(JTable table, String tableTitle) {
        // TODO Auto-generated constructor stub
        this.setTable(table);
        // Sets the table header
        headerFormat = new MessageFormat(tableTitle);
        // Sets the table footer
        footerFormat = new MessageFormat("Page {0}");

        try {
            boolean complete = table.print(JTable.PrintMode.FIT_WIDTH,
                    headerFormat, footerFormat, true, null, true, null);

            if (complete) {
                new ConfirmationClass(
                        "<html><h2>Records Printed Successfully</h2></html>");
            }

        } catch (HeadlessException | PrinterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @return the table
     */
    public JTable getTable() {
        return table;
    }

    /**
     * @param table
     *            the table to set
     */
    public void setTable(JTable table) {
        this.table = table;
    }
}

答案 1 :(得分:0)

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
             //TODO Auto-generated method stub
                MessageFormat header=new MessageFormat("Your Invoice");
                MessageFormat footer=new MessageFormat("Page");
            try 
            {

                table.print(JTable.PrintMode.FIT_WIDTH, header, footer);
            }

            catch(Exception ae)
            { 
                System.err.println("Error printing: " + ae.getMessage());

                }
        }
    });

这可能会有所帮助:)