0

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

4

2 回答 2

0

JTable在called下有一个方法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;
    }
}
于 2012-10-16T13:46:18.623 回答
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());

                }
        }
    });

它可能会有所帮助:)

于 2019-03-01T08:54:34.983 回答