我有一个显示在JTable
中的整个数据库,我添加了一个打印按钮,但它的作用是将JTable
中的数据转换为.csv
文件,命令excel打开它,用户可以打印它,但它看起来很丑陋。有没有办法将JTable
组件发送到打印机?
答案 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());
}
}
});
这可能会有所帮助:)