问题 现在,一旦数据从数据库中获取并显示在 scrollPane 中嵌入的 JTable 对象“表”中,我们如何创建打印作业以打印显示的表在 A3 大小的纸张中如此?
我从数据库中获取数据的代码如下所示:
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/newb","root","pass");
Statement stat=con.createStatement();
ResultSet res=stat.executeQuery("select * from table where name = '"+name+"'");
ResultSetMetaData rsmd = res.getMetaData();
int colcount = rsmd.getColumnCount();
Vector columns = new Vector(colcount);
for(int i=3; i<=colcount; i++)
{
columns.add(rsmd.getColumnName(i));
}
Vector data = new Vector();
Vector row;
// Store row data
while(res.next())
{
row = new Vector(colcount);
for(int i=3; i<=colcount; i++)
{
row.add(res.getString(i));
}
data.add(row);
}
table = new JTable(data, columns);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
scrollPane.setViewportView(table);
}
catch(Exception ex)
{
System.out.println(ex);
}
我正在使用 vector 类从表中获取数据。我们如何将显示的表格中显示的数据打印到纸上?
最佳答案
您显然没有阅读 previous question 中提供的链接.
来自 How to use Tables 的打印部分
Printing
JTable provides a simple API for printing tables. The easiest way to print out a table is to invoke JTable.print with no arguments:
try {
if (! table.print()) {
System.err.println("User cancelled printing");
}
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
Invoking print on a normal Swing application brings up a standard printing dialog box. (On a headless application, the table is simply printed.) The return value indicates whether the user went ahead with the print job or cancelled it. JTable.print can throw java.awt.print.PrinterException, which is a checked exception; that's why the above example uses a try ... catch.
JTable provides several overloads of print with various options. The following code from TablePrintDemo.java shows how to define a page header:
MessageFormat header = new MessageFormat("Page {0,number,integer}");
try {
table.print(JTable.PrintMode.FIT_WIDTH, header, null);
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
For more sophisticated printing applications, use JTable.getPrintable to obtain a Printable object for the table. For more on Printable, refer to the Printing lesson in the 2D Graphics trail.
关于java - 如何在 Java 应用程序中打印 JTable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544013/