1

I want to print JTable and JLabel's using java swing. I have tried the below code, it's printing only JLabel values. JTable is not printing.

Kindly help.

Code:

public class TablePrintDemo1 extends JPanel implements Printable, ActionListener {

        private static final long serialVersionUID = 1L;
        static JFrame frameToPrint;
        JLabel l1, l2, l3, l4, l5, l6, l7, l8;
        JTextField t1, t2, t3, t4, t5;
        JButton printButton;
        DefaultTableModel model = new DefaultTableModel();
        JTable tabGrid = new JTable(model);
        JScrollPane scrlPane = new JScrollPane(tabGrid);
        static Vector<Object> tableValues = new Vector<Object>();
        static List<String> dataValues = new ArrayList<String>();

        public TablePrintDemo1(Vector<Object> tableValues,
                List<String> dataValues) {
            setLayout(null);
            setVisible(true);
            frameToPrint = new JFrame("Sample Table");
            l1 = new JLabel("Silver Shop ");
            l1.setBounds(100, 70, 550, 40);
            add(l1);

            Font f = new Font("Berlin Sans FB Demi", Font.BOLD, 40);
            l1.setFont(f);

            l2 = new JLabel(
                    "Address_Line1, Address_Line2, City, Pin Code.");
            l2.setBounds(40, 120, 550, 40);
            add(l2);

            l2.setFont(new Font("Courier New", Font.BOLD, 15));

            l3 = new JLabel("Bill Number ");
            l7 = new JLabel();

            l7.setFont(new Font("Courier New", Font.BOLD, 20));

            //      t1 = new JTextField(20);
            l3.setBounds(70, 180, 150, 20);
            l7.setBounds(150, 180, 120, 20);
            l7.setText(dataValues.get(0));
            add(l3);
            add(l7);

            l4 = new JLabel("Bill Date");
            l8 = new JLabel();
            l4.setBounds(300, 180, 200, 20);
            l8.setBounds(400, 180, 200, 20);
            l8.setText(dataValues.get(2));
            l7.setFont(new Font("Courier New", Font.BOLD, 12));

            add(l4);
            add(l8);

            model.addColumn("Product Name");
            model.addColumn("Quantity");
            model.addColumn("Price (1 gram)");
            model.addColumn("Total No.of grams");
            model.addColumn("Amount");
            scrlPane.setBounds(50, 220, 500, 350);
            frameToPrint.add(scrlPane);
            tabGrid.setFont(new Font("Latha", Font.PLAIN, 12));

            for (Object v : tableValues) {
                model.addRow((Vector) v);
                System.out.println("Object Values : " + v);
            }

            l5 = new JLabel("Total Amount");
            l5.setBounds(300, 570, 500, 20);
            l5.setFont(new Font("Times New Roman", 1, 20));
            add(l5);

            l6 = new JLabel();
            l6.setBounds(420, 570, 500, 20);
            l6.setFont(new Font("Times New Roman", 1, 20));
            l6.setText(dataValues.get(1));
            add(l6);

            printButton = new JButton("Print");
            printButton.addActionListener(this);
            frameToPrint.add("South", printButton);
            frameToPrint.getContentPane().add(this);
            tabGrid.setOpaque(false);
            printButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    printButton.setVisible(false);
                }
            });
        }

        /*@Override
        public void actionPerformed(ActionEvent e) {
            printButton.setVisible(false);
        }*/

        public static void main(String a[]) {
            dataValues.add("12");
            dataValues.add("760.00");
            dataValues.add("08/06/2015");           

            TablePrintDemo1 tablePrintDemo1 = new TablePrintDemo1(tableValues, dataValues);
            frameToPrint.add(tablePrintDemo1);
            frameToPrint.setSize(700, 680);
            frameToPrint.setBackground(Color.WHITE);
            frameToPrint.show();
        }

        public int print(Graphics g, PageFormat pf, int page)
                throws PrinterException {

            if (page > 0) { /* We have only one page, and 'page' is zero-based */
                return NO_SUCH_PAGE;
            }

            Graphics2D g2 = (Graphics2D) g;
            g2.translate(pf.getImageableX(), pf.getImageableY() - 55);

            AffineTransform originalTransform = g2.getTransform();

            double scaleX = pf.getImageableWidth() / this.getWidth();
            double scaleY = pf.getImageableHeight() / this.getHeight();
            // Maintain aspect ratio
            double scale = Math.min(scaleX, scaleY);
            g2.translate(pf.getImageableX(), pf.getImageableY());
            g2.scale(scale, scale);
            g2.setTransform(originalTransform);

            this.printAll(g2);

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

        public void actionPerformed(ActionEvent e) {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPrintable(this);
            boolean ok = job.printDialog();
            if (ok) {
                try {
                    job.print();
                } catch (PrinterException ex) {
                    ex.printStackTrace();
                }
            }
        }

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ramesh
  • 23
  • 5

1 Answers1

1

Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

You've added the JScrollPane to the JFrame...

frameToPrint.add(scrlPane);

Then added the JPanel to the same JFrame

frameToPrint.getContentPane().add(this);

It's kind of a fluke that the JScrollPane is been rendered above the JPanel, but when you call this.printAll, it's not printing the JScrollPane because it's not contained within the JPanel at all.

I'd recommend having a look at Jasper Reports, you might even be able to make use of the JTable's in built printing support directly instead, for example

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Genius. Many thanks for the immediate response. I have removed JScrollPane and added it to JPanel. Issue resolved. Now it's printing both JTable and JLabel. – Ramesh Jun 11 '15 at 06:12
  • English characters are printing perfectly. But when I use other than english I'm getting below error message, Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 11 at sun.font.ExtendedTextSourceLabel.getJustificationInfos(Unknown Source) at java.awt.font.TextLine.getJustifiedLine(Unknown Source) at java.awt.font.TextLayout.getJustifiedLayout(Unknown Source) at sun.swing.SwingUtilities2.drawString(Unknown Source) at sun.swing.SwingUtilities2.drawStringUnderlineCharAt(Unknown Source) – Ramesh Jun 11 '15 at 07:06
  • It could be an issue with Unicode support for the font or an issue with the printer driver – MadProgrammer Jun 11 '15 at 07:36
  • Issue is not with the printer. I have tested with sample print. I have set Unicode UTF-8 in the java file. Values are inside JTable and let me know how to set UTF-8 to print other language. – Ramesh Jun 11 '15 at 09:41