[英]How to print a JTable object in the Java application
問題現在,一旦從數據庫中獲取數據並將其顯示在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);
}
我正在使用向量類從表中獲取數據。 我們如何將顯示在表格中的數據打印到紙張上?
只需使用JTable.print()
方法。 這是一篇有關將JTable發送到打印機中的文章,以及另一篇包含更多參數的文章
您顯然沒有閱讀上一個問題中提供的鏈接。
從“ 如何使用表格”的“打印”部分
列印
JTable提供了一個用於打印表的簡單API。 打印表的最簡單方法是不帶任何參數調用JTable.print:
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());
}
在普通的Swing應用程序上調用打印會彈出一個標准的打印對話框。 (在無頭應用程序中,僅打印表。)返回值指示用戶是繼續打印作業還是取消打印作業。 JTable.print可以拋出java.awt.print.PrinterException,這是一個已檢查的異常; 這就是為什么上面的示例使用try ... catch的原因。
JTable提供了多種帶有各種選項的打印重載。 TablePrintDemo.java中的以下代碼顯示了如何定義頁面標題:
MessageFormat標頭=新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());
}
對於更復雜的打印應用程序,請使用JTable.getPrintable獲取表的Printable對象。 有關“可打印”的更多信息,請參考“ 2D圖形”軌跡中的“打印”課程。
我希望此代碼可以幫助您嘗試一下如何在Java netbeans中打印JTable
private void btn_printActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MessageFormat header = new MessageFormat("Print Report");
MessageFormat footer = new MessageFormat("Page{0,number,integer}");
try {
table_employee.print(JTable.PrintMode.FIT_WIDTH, header, footer);
} catch (java.awt.print.PrinterAbortException e) {
} catch (PrinterException ex) {
Logger.getLogger(employee_info.class.getName()).log(Level.SEVERE, null, ex);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.