How to print a JTable object in the Java application

前端 未结 3 650
一整个雨季
一整个雨季 2020-11-30 15:36

Question Now once the data is fetched from the database and shown in the JTable object \"table\" embedded in the scrollPane, how do we create a print job th

3条回答
  •  醉梦人生
    2020-11-30 16:30

    You obviously didn't read the links provided in your previous question.

    From the Printing section of 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.

提交回复
热议问题