在模板上打印JTable以适合A4纸张

时间:2013-11-26 10:18:49

标签: java swing printing

我目前正在开展一项任务,涉及在预先定义的模板上打印JTable,例如附图中显示的模板。

enter image description here

我的方法是打印包含表格的JFrame,因为我已将附加图像设置为JFrame的背景。

然后我创建了一个实现Printable对象的PrintUIWindow。这个PrintUIWindow接受JFrame的对象作为其构造函数的参数打印。

上述方法对我不起作用:

首先,因为我正在打印JFrame,只有我的可见部分    JTable已打印。这是我想要打印的主要问题    我的整个JTable在不同页面上的模板上假设数字    JTable中的行数超过了可以打印在单个行中的行数    页。

其次,JFrame不适合A4纸。基本上我已经有了    将图像调整到550x778的高度,这是相同的高度和    我正在传递的JFrame的宽度用于打印。这是唯一的    我已经能够将JFrame和内容放在A4纸上了。

第三,减小了图像的大小以匹配JFrame    (当打印时适合A4纸张),打印输出的质量    由于上述模板的质量低,因此像素化    我正在使用的图像作为JFrame的背景图像    打印。

以下是我要打印的框架的代码:

    package bge.applcs.dsa;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseListener;
import java.awt.image.ImageObserver;
import java.awt.print.PrinterException;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.ScrollPaneLayout;
import javax.swing.Timer;
import javax.swing.border.LineBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import bge.applcs.dsa.LogInDesktopPane.MyLayout;

public class DSAAccessPrintPreview extends JFrame {

    /** Public vars */
    public PrintPreviewFrame printPreviewFrame;
    public PrintPreviewFramePanel printPreviewFramePanel;
    public JTable authTable;
    public static AuthScrollPane authTableScrollPane;
    public BGEDSATableModel bgeDSATableModel;
    public String officialBoldFontLocation = "\\" + "\\C:\\NewFolder\\SquareSevenTwoOneBold.ttf";
    public String officialRegularFontLocation = "\\" + "\\C:\\NewFolder\\SquareSevenTwoOneRegular.ttf";
    public static Font officialFontBold, officialFontBold2;
    public Font officialFontRegular,  officialFontRegular2;
    public static JLabel notifMssgLabel;
    public Container con = null;
    public Color genericPanelBackgrounds;
    public String UnencryptedString, textFromAgentIDJTextField, textFromUnameJTextField, textFromPwrdJTextField;
    public String[] fileDataAsStringArray;
    public JTextField agentIDJTextField, unameJTextField, pwrdJTextField;
    public static String userHasOpenedUsageStatsScnValue;
    public static JButton btnDSAAccess, btnUsageStats, btnExit, btnAddNew, btnDelete, btnSaveAll, btnUpdate, btnPrint;
    public static Timer timerCreateUsageStatsJIFrame;
    public static String userUsageStatsScnActionFilePath = "\\" + "\\C:\\NewFolder\\hasuseropenedusagestatsscn.txt";
    public String unEncryptedDataFilePath = "\\" + "\\C:\\NewFolder\\UnencryptedBGEDSAAuthData.txt";

    //!< Print preview constructor
    public DSAAccessPrintPreview() {
        super();

        // Create panel object
        printPreviewFramePanel = new PrintPreviewFramePanel();

        // Set the contentPane which is the primary container for application specific components.
        setContentPane((printPreviewFramePanel));

        // Enable moving of JFrame by creating a custom mouselistener to monitor mouse movements
        MoveMouseListener mml = new MoveMouseListener(printPreviewFramePanel);
        printPreviewFramePanel.addMouseListener(mml);
        printPreviewFramePanel.addMouseMotionListener(mml);

        // Remove the default border i.e. minimize, max and close btns
        setUndecorated(true);

        // Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
        pack();

        // Shows or hides this Window depending on the value of parameter - true means show the window
        setVisible(false);

        // Sets whether this frame is resizable by the user.
        setResizable(false);

        // Sets the operation that will happen by default when the user initiates a "close" on this frame - here the choice is EXIT_ON_CLOSE
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Sets the location of the window relative to the specified component which in this case is null meaning the window is placed in the center of the screen.
        setLocationRelativeTo(null);        

        // Enable escape to close the window by first returning the rootPane object for this frame, 
        // then the InputMap that is used during condition i.e. JComponent.WHEN_IN_FOCUSED_WINDOW
        // and then use function put to add a binding for keyStroke to actionMapKey
        KeyStroke ks_esc = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        getRootPane().getInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW).put(ks_esc, "Cancel");
    }

    /*! Print Preview Frame Panel */
    public class PrintPreviewFramePanel extends JPanel {

        //!< Panel Constructor
        public PrintPreviewFramePanel() {
            createPanel();
        }

        //!< Override the paint method to draw the background image
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            // Fetch background image dimensions.
            ImageIcon img = new ImageIcon((getClass().getClassLoader().getResource("bgnduseraccessprintout.jpg")));

            // Draw/paint the background image
            img.paintIcon(this, g, 0, 0);
        }

        //!< Create respective JFrame JPanel
        public void createPanel() {

            System.out.println("\n**********************************************************************"); 
            System.out.println("Start of print preview panel");
            System.out.println("*************************************************************************"); 

            // Set the LayoutManager. Overridden to conditionally forward the call to the contentPane.
            setLayout(null);

            // Set the prefered size for the main content panel
            setPreferredSize(new Dimension(550, 778));

            // *************************************************************************
            // Table
            // *************************************************************************
            // Create and prepare object from custom table model
            bgeDSATableModel = new BGEDSATableModel();

            // Create and customise table
            authTable = new JTable(bgeDSATableModel);        
            authTable.setFillsViewportHeight(true);
            authTable.setAutoCreateRowSorter(false);
            authTable.setFont(officialFontRegular2);

            int height = authTable.getRowHeight();
            authTable.setRowHeight(height+1);

            // Customise table header
            authTable.getTableHeader().setBackground(new Color(7, 0, 0, 1));
            authTable.getTableHeader().setForeground(new Color(7, 0, 0, 1));
            authTable.getTableHeader().setFont(officialFontRegular2);
            authTable.getTableHeader().setReorderingAllowed(false);
            authTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

            //
            for(MouseListener mouseListener : authTable.getTableHeader().getMouseListeners()) {
                authTable.getTableHeader().removeMouseListener(mouseListener);
            }

            // 
            JLabel colZeroLabel = new JLabel("COLUMN 0");
            LineBorder headerBorder = new LineBorder(Color.ORANGE, 0, true);
            colZeroLabel.setForeground(new Color(7, 0, 0, 1));
            colZeroLabel.setBackground(new Color(7, 0, 0, 1));
            colZeroLabel.setBorder(headerBorder);

            JLabel colOneLabel = new JLabel("COLUMN 1");
            colOneLabel.setForeground(new Color(7, 0, 0, 1));
            colOneLabel.setBackground(new Color(7, 0, 0, 1));
            colOneLabel.setBorder(headerBorder);

            JLabel colTwoLabel = new JLabel("COLUMN 2");
            colTwoLabel.setForeground(new Color(7, 0, 0, 1));
            colTwoLabel.setBackground(new Color(7, 0, 0, 1));
            colTwoLabel.setBorder(headerBorder);

            JLabel colThreeLabel = new JLabel("COLUMN 3");
            colThreeLabel.setForeground(new Color(7, 0, 0, 1));
            colThreeLabel.setBackground(new Color(7, 0, 0, 1));
            colThreeLabel.setBorder(headerBorder);

            //
            TableCellRenderer renderer = new JComponentTableCellRenderer();
            TableColumnModel columnModel = authTable.getColumnModel();

            TableColumn column0 = columnModel.getColumn(0);
            column0.setHeaderRenderer(renderer);
            column0.setHeaderValue(colZeroLabel);

            TableColumn column1 = columnModel.getColumn(1);
            column1.setHeaderRenderer(renderer);
            column1.setHeaderValue(colOneLabel);

            TableColumn column2 = columnModel.getColumn(2);
            column2.setHeaderRenderer(renderer);
            column2.setHeaderValue(colTwoLabel);

            TableColumn column3 = columnModel.getColumn(3);
            column3.setHeaderRenderer(renderer);
            column3.setHeaderValue(colThreeLabel);

            // Adjust table column widths
            columnModel.getColumn(0).setPreferredWidth(77);
            columnModel.getColumn(1).setPreferredWidth(105);
            columnModel.getColumn(2).setPreferredWidth(68);
            columnModel.getColumn(3).setPreferredWidth(102);

            try {
                fileDataAsStringArray = getStringFromFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Pass data from UnencryptedBGEDSAAuthData.txt to be sorted and added to table
            bgeDSATableModel.sortDataIntoTable(fileDataAsStringArray);

            // Create and customise auth table scrollpane
            authTableScrollPane = new AuthScrollPane(authTable);
            authTableScrollPane.setBounds(19, 108, 510, 600);

            LineBorder lineBorder = new LineBorder(Color.ORANGE, 0, true);
            authTableScrollPane.setBorder(lineBorder);

            authTableScrollPane.setOpaque(false);
            authTableScrollPane.getViewport().setOpaque(false);
            authTableScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            authTableScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

            // Add table to main panel
            add(authTableScrollPane);

            /*JTable.PrintMode mode = JTable.PrintMode.FIT_WIDTH;

            //
            try {
                authTable.print(mode, null, null, true, null, true, null);
            } catch (HeadlessException e) {
                e.printStackTrace();
            } catch (PrinterException e) {
                e.printStackTrace();
            }*/
        }

        //!< Get string from file/Read decrypted data from file
        public String[] getStringFromFile() throws IOException {

            System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - " +
                    "\nSTEP 3 b - READ FROM FILE INTO A STRING ARRAY\n- - - - - - - - - - - - - - - - - - - - - - - - - - -"); 

            String filePath = "\\" + "\\C:\\NewFolder\\UnencryptedBGEDSAAuthData.txt";

            // Create and prepare FileInputStream and feed it the file name
            FileInputStream fstream;

            try {
                fstream = new FileInputStream(filePath);
                            // use DataInputStream to read binary NOT text
                // Don't Create and prepare the object of DataInputStream
                // DataInputStream in = new DataInputStream(fstream);

                // Create and prepare the object of the BufferedReader 
                BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

                // Create and prepare string in which the file info will be rendered
                String strLine;

                // Read through file content and display in reverse order in System.out
                for (strLine = br.readLine();  strLine != null;  strLine = br.readLine()) {
                    StringBuilder builder = new StringBuilder(strLine);  

                    UnencryptedString = builder.toString(); 
                }

                //Close the input stream
                in.close();

            } catch (FileNotFoundException e) {

                // Throw error mssg that file has not been found
                //alertFileNotFound(filePath);

                System.out.println("STEP 3 b - getStringFromFile() - " + "Error - File not found. Why?"  + e.toString());

                //e.printStackTrace();
            }

            String delims_scolon = "[;]";

            // Use delimiters to separate content file content 
            String[] fileDataAsStringArray = UnencryptedString.split(delims_scolon);

            for(int i = 0; i < fileDataAsStringArray .length ; i++) {
                System.out.println("STEP 3 b - getStringFromFile() - " + "Data in row " + i + " of File Data String Array is: " + fileDataAsStringArray[i]);
            }

            return fileDataAsStringArray;
        }

    }

    // Create and prepare custom table model for data entry
    public class BGEDSATableModel extends AbstractTableModel {

         private String[] columnNames = {"COL1", "COL2", "COL3", "COL4"};
         private Vector data = new Vector();
         protected int[] row;
         protected int sortColumn;

         public BGEDSATableModel() {
             //sortColumn = sortcolumn;
         }

         // Get table row count
         @Override
         public int getRowCount() {
            return data.size();
         }

         // Get column count
         @Override
         public int getColumnCount() {
             return columnNames.length;
         }

         // Get cell value
         @SuppressWarnings("rawtypes")
         @Override
         public Object getValueAt(int row, int col) {
             //System.out.println("((Vector) data.get(row)).get(col) in row " + row + " and column " + col + " is: " + ((Vector) data.get(row)).get(col));

             return ((Vector) data.get(row)).get(col);
         }

         // Get column name
         public String getColumnName(int col){
             return columnNames[col];
         }

         // Get column class
         public Class getColumnClass(int c){
             return getValueAt(0,c).getClass();
         }

         // Set value at
         public void setValueAt(Object value, int row, int col){
             ((Vector) data.get(row)).setElementAt(value, col);
             fireTableCellUpdated(row,col);
         }

         public boolean isCellEditable(int row, int col){
             if (row == 0) {
                 return false;
             }

             return true;
         }

         // STEP 4 - Sort data into table
         public void sortDataIntoTable(String[] fileDataAsStringArray) {

            for(int i = 0; i < fileDataAsStringArray.length ; i++) {
                System.out.println("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - " +
                        "\nSTEP 4 - SORT STRING ARRAY/DATA INTO TABLE\n- - - - - - - - - - - - - - - - - - - - - - - - - - -"); 

                System.out.println("STEP 4 - Data in row " + i + " of File Data String Array is: " + fileDataAsStringArray[i]);

                String[] tableContent = fileDataAsStringArray[i].split(",");

                System.out.println("STEP 4 - After split data in row " + i + " - column 0 and  of table content array is: " + tableContent[0]);
                System.out.println("STEP 4 - After split data in row " + i + " - column 1 and  of table content array is: " + tableContent[1]);
                System.out.println("STEP 4 - After split data in row " + i + " - column 2 and  of table content array is: " + tableContent[2]);
                System.out.println("STEP 4 - After split data in row " + i + " - column 3 and  of table content array is: " + tableContent[3]);

                Object[] values = {tableContent[0], tableContent[1], tableContent[2], tableContent[3]};

                //System.out.println("STEP 4 - Values in row " + i + " is: " + values[i]);

                insertDataFromFile(values);
            }

            // Notify user that file has been successfully read and the file data has been sorted into the table
            //fileCorrectlyReadAndSortedIntoTable();
         }       

         // STEP 4 - Inserting of data into table
         public void insertDataFromFile(Object[] values){
             System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - \nSTEP 4 - INSERT DATA FROM FILE INTO TABLE\n- - - - - - - - - - - - - - - - - - - - - - - - - - -"); 

             data.add(new Vector());

             System.out.println("STEP 4 - Length of values is: " + values.length);

             for(int i = 0; i < values.length; i++){

                 ((Vector) data.get(data.size()-1)).add(values[i]);

                 System.out.println("STEP 4 - Value " + i + " has been added.");
             } 

             // Update 
             fireTableDataChanged();
         }

         // STEP 5 a - Numb of rows
         public int numbOfRows() {

             System.out.println("STEP 5 a - Row count using getRowCount() is: " + getRowCount());

             return getRowCount();
         }

    }

    //
    class AuthScrollPane extends JScrollPane {

        public AuthScrollPane(Component view) {
            super(view, VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS);

            this.setLayout(new MyLayout());

            //setBackground(Color.red);
        }
    }

    //
    class MyLayout extends ScrollPaneLayout {

        public MyLayout() {
            super();
        }

        public void layoutContainer(Container parent) {
            super.layoutContainer(parent);

            vsb.setSize(vsb.getWidth() , vsb.getHeight());
            LineBorder lineBorder = new LineBorder(Color.ORANGE, 1, true);
            vsb.setBorder(lineBorder);
            vsb.setBackground(Color.RED);
            vsb.setOpaque(false);

            //hsb.setSize(0, 0); // drift
            //hsb.setEnabled(false);
        }  
    }

    //
    class JComponentTableCellRenderer implements TableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {

            return (JComponent) value;
        }
    }

}

以下是上述PrintUIWindow的代码:

    package bge.applcs.dsa;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;

/*! Print UI Window */
public class PrintUIWindow implements Printable, ActionListener {

    /** Public vars */
    JFrame frameToPrint;

    //!< Print UI Window constructor 
    public PrintUIWindow(JFrame f) {
        frameToPrint = f;
    }

    //!< Prints the page at the specified index into the specified Graphics context in the specified format. A PrinterJob calls the Printable interface to request that a page be rendered into the context specified by graphics. The format of the page to be drawn is specified by pageFormat. The zero based index of the requested page is specified by pageIndex. If the requested page does not exist then this method returns NO_SUCH_PAGE; otherwise PAGE_EXISTS is returned. The Graphics class or subclass implements the PrinterGraphics interface to provide additional information. If the Printable object aborts the print job then it throws a PrinterException.
    public int print(Graphics g, PageFormat pf, int page) throws PrinterException {

        System.out.println("\n - * - * - * - START OF  print(Graphics g, PageFormat pf, int page) ");

        //
        System.out.println("\nprint(Graphics g, PageFormat pf, int page) - g returns: " + g);
        System.out.println("\nprint(Graphics g, PageFormat pf, int page) - pf returns: " + pf);
        System.out.println("\nprint(Graphics g, PageFormat pf, int page) - page returns: " + page);

        // Assuming the page value which is the zero based index of the page to be drawn is zero then go ahead and print.
        // If it isn't then indicate that no such page exists.
        if (page > 0) { /* We have only one page, and 'page' is zero-based */
            System.out.println("\nprint(Graphics g, PageFormat pf, int page) - page returns: " + page + " hence NO_SUCH_PAGE is returned.");

            return NO_SUCH_PAGE;
        }

        /* User (0,0) is typically outside the imageable area, so we must
         * translate by the X and Y values in the PageFormat to avoid clipping
         */
        Graphics2D g2d = (Graphics2D)g;

        System.out.println("\nprint(Graphics g, PageFormat pf, int page) - pf.getImageableX() returns: " + pf.getImageableX() + 
                            " - pf.getImageableY() returns: " + pf.getImageableY());

        g2d.translate(3, 3);

        /* Now print the window and its visible contents */
        frameToPrint.printAll(g);

        System.out.println("\nprint(Graphics g, PageFormat pf, int page) - frameToPrint.printAll(g); has been called."); 

        System.out.println("\n - * - * - * - END OF  print(Graphics g, PageFormat pf, int page) ");

        /* tell the caller that this page is part of the printed document */
        return PAGE_EXISTS;
    }

    //!< Override the method actionPerformed(ActionEvent e) from interface ActionListener
    public void actionPerformed(ActionEvent e) {
         // Enable visibility of print preview frame
         frameToPrint.setVisible(true);

         // The PrinterJob class is the principal class that controls printing. An application calls methods in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job.
         PrinterJob job = PrinterJob.getPrinterJob();

         // Calls painter to render the pages. The pages in the document to be printed by this PrinterJob are rendered by the Printable object, painter. The PageFormat for each page is the default page format.
         job.setPrintable(this);

         // Presents a dialog to the user for changing the properties of the print job. This method will display a native dialog if a native print service is selected, and user choice of printers will be restricted to these native print services. 
         boolean ok = job.printDialog();

         System.out.println("\nactionPerformed(ActionEvent e) - ok is: " + ok); 

         // Check if true is returned from the print dialog. If it is then go ahead and print. 
         if (ok) {
             try {

                 //
                 job.print();

                 System.out.println("\nactionPerformed(ActionEvent e) - Since ok is " + ok + " job.print(); has just been executed."); 

             } catch (PrinterException ex) {
                 // The job did not successfully complete

                 System.out.println("\nactionPerformed(ActionEvent e) - The job did not successfully complete."); 
             }

             // Disable visibility of print preview frame
             frameToPrint.setVisible(false);
         } else {
             System.out.println("\nactionPerformed(ActionEvent e) - Since ok is " + ok + " job.print(); has NOT been executed.");

             // Disable visibility of print preview frame
             frameToPrint.setVisible(false);
         }
    }
}

以下是我从主JFrame调用打印操作的方法:

DSAAccessPrintPreview printPreviewFrame = new DSAAccessPrintPreview();
btnPrint.addActionListener(new PrintUIWindow(printPreviewFrame));

我感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

JTable类支持打印,因此尝试调用JTable print()方法而不是尝试打印JFrame。有关示例代码,请查看http://docs.oracle.com/javase/tutorial/uiswing/misc/printtable.html