0

I have a system where the user can register students, subjects, and the student grade in each subject, together with the topic and the date. You can search a particular student grades in a particular subject by entering the code of the student, and by selecting the subject from a combobox. If you search it, those things are displayed in the jTable1.

Then, I have a PRINT button. When the user clicks the Print button, the content that is being displayed in the jTable1, goes to a jTable2, the difference between those 2 tables is that the jTable1 displays the name of the student, and the name of the subject, but the jTable2 doesn't. Here is a pic for better understanding:

imagehttps://i.stack.imgur.com/37SNh.png

So, when the user clicked the button to Print the jTable2, I was using this code right here:

        MessageFormat header = new MessageFormat("Ficha Pedagógica - "+jComboBox1.getSelectedItem());

    MessageFormat footer = new MessageFormat("Página {0,number,integer}");

    try{
        jTable2.print(JTable.PrintMode.NORMAL, header, null);
    }
    catch(java.awt.print.PrinterException e){
        System.out.println("error");
    }

The fact is, that I wanted 2 headlines to be printed, but such thing couldn't be achieved using the built-in print function. So, here in Stack Overflow, I found this topic:

How to print multiple header lines with MessageFormat using a JTable

After I found this, I tried using the code given there. Since I'm a beginner, even with all the comments in the code, I couldn't fully understand it. So, I tried to implement it, but now, when I click the "Print" button, nothing happens. This is my code of the Print button:

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
        try{
        Class.forName(driver);
        con = DriverManager.getConnection(str_conn,usuario,senha);
        stmt = con.createStatement();
        sql = "select topico, nota, datanota from notas where notas.cod_aluno ="+jTextField1.getText()+" and notas.cod_curso ="+jTextField2.getText()+" order by notas.datanota";
        rs = stmt.executeQuery(sql);
        if(rs == null){
            return;
        }
        ResultSetMetaData rsmd;
        rsmd = rs.getMetaData();
        Vector vetColuna = new Vector();
        for(int i = 0;i<rsmd.getColumnCount();i++){
            vetColuna.add(rsmd.getColumnLabel(i+1));
        }
        Vector vetLinhas = new Vector();

        while(rs.next()){
            Vector vetLinha = new Vector();
            for(int i = 0;i<rsmd.getColumnCount();i++){
                vetLinha.add(rs.getObject(i+1));
            }
            vetLinhas.add(vetLinha);
            jTable2.setModel(new DefaultTableModel(vetLinhas,vetColuna));
        }
    }catch(ClassNotFoundException ex){
        JOptionPane.showMessageDialog(null,"Erro\nNão foi possível carregar o driver.");
        System.out.println("Nao foi possivel carregar o driver");
        ex.printStackTrace();
    }catch(SQLException ex){
        JOptionPane.showMessageDialog(null,"Erro\nCertifique-se de que todos os\ncampos estejam preenchidos corretamente.");
        System.out.println("Problema com o SQL");
        ex.printStackTrace();
    }

    /*MessageFormat header = new MessageFormat("Ficha Pedagógica - "+jComboBox1.getSelectedItem());

    MessageFormat footer = new MessageFormat("Página {0,number,integer}");

    try{
        jTable2.print(JTable.PrintMode.NORMAL, header, null);
    }
    catch(java.awt.print.PrinterException e){
        System.out.println("gsgd");
    }*/    
DefaultTableModel dtm = new DefaultTableModel(new String[] { "Column 1" }, 1);
JTable jTable2 = new JTable(dtm) {
@Override
public Printable getPrintable(PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) {
   return new TablePrintable(this, printMode, headerFormat, footerFormat);
        }
    };
}         

The code for the "TablePrintable" class is the following:

static class TablePrintable implements Printable {

    private final JTable table;
    private final JTableHeader header;
    private final TableColumnModel colModel;
    private final int totalColWidth;
    private final JTable.PrintMode printMode;
    private final MessageFormat headerFormat;
    private final MessageFormat footerFormat;
    private int last = -1;
    private int row = 0;
    private int col = 0;
    private final Rectangle clip = new Rectangle(0, 0, 0, 0);
    private final Rectangle hclip = new Rectangle(0, 0, 0, 0);
    private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
    private static final int H_F_SPACE = 8;
    private static final float HEADER_FONT_SIZE = 18.0f;
    private static final float FOOTER_FONT_SIZE = 12.0f;
    private final Font headerFont;
    private final Font footerFont;

    public TablePrintable(JTable table, JTable.PrintMode printMode, MessageFormat headerFormat,
            MessageFormat footerFormat) {

        this.table = table;

        header = table.getTableHeader();
        colModel = table.getColumnModel();
        totalColWidth = colModel.getTotalColumnWidth();

        if (header != null) {
            // the header clip height can be set once since it's unchanging
            hclip.height = header.getHeight();
        }

        this.printMode = printMode;

        this.headerFormat = headerFormat;
        this.footerFormat = footerFormat;

        // derive the header and footer font from the table's font
        headerFont = table.getFont().deriveFont(Font.BOLD, HEADER_FONT_SIZE);
        footerFont = table.getFont().deriveFont(Font.PLAIN, FOOTER_FONT_SIZE);
    }

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {

        // for easy access to these values
        final int imgWidth = (int) pageFormat.getImageableWidth();
        final int imgHeight = (int) pageFormat.getImageableHeight();

        if (imgWidth <= 0) {
            throw new PrinterException("Width of printable area is too small.");
        }

        // to pass the page number when formatting the header and footer
        // text
        Object[] pageNumber = new Object[] { Integer.valueOf(pageIndex + 1) };

        // fetch the formatted header text, if any
        String headerText = null;
        if (headerFormat != null) {
            headerText = headerFormat.format(pageNumber);
        }

        // fetch the formatted footer text, if any
        String footerText = null;
        if (footerFormat != null) {
            footerText = footerFormat.format(pageNumber);
        }

        // to store the bounds of the header and footer text
        Rectangle2D hRect = null;
        Rectangle2D fRect = null;

        // the amount of vertical space needed for the header and footer
        // text
        int headerTextSpace = 0;
        int footerTextSpace = 0;

        // the amount of vertical space available for printing the table
        int availableSpace = imgHeight;

        // if there's header text, find out how much space is needed for it
        // and subtract that from the available space
        if (headerText != null) {
            graphics.setFont(headerFont);
            int nbLines = headerText.split("\n").length;
            hRect = graphics.getFontMetrics().getStringBounds(headerText, graphics);

            hRect = new Rectangle2D.Double(hRect.getX(), Math.abs(hRect.getY()), hRect.getWidth(),
                    hRect.getHeight() * nbLines);

            headerTextSpace = (int) Math.ceil(hRect.getHeight() * nbLines);
            availableSpace -= headerTextSpace + H_F_SPACE;
        }

        // if there's footer text, find out how much space is needed for it
        // and subtract that from the available space
        if (footerText != null) {
            graphics.setFont(footerFont);
            fRect = graphics.getFontMetrics().getStringBounds(footerText, graphics);

            footerTextSpace = (int) Math.ceil(fRect.getHeight());
            availableSpace -= footerTextSpace + H_F_SPACE;
        }

        if (availableSpace <= 0) {
            throw new PrinterException("Height of printable area is too small.");
        }

        // depending on the print mode, we may need a scale factor to
        // fit the table's entire width on the page
        double sf = 1.0D;
        if (printMode == JTable.PrintMode.FIT_WIDTH && totalColWidth > imgWidth) {

            // if not, we would have thrown an acception previously
            assert imgWidth > 0;

            // it must be, according to the if-condition, since imgWidth > 0
            assert totalColWidth > 1;

            sf = (double) imgWidth / (double) totalColWidth;
        }

        // dictated by the previous two assertions
        assert sf > 0;

        // This is in a loop for two reasons:
        // First, it allows us to catch up in case we're called starting
        // with a non-zero pageIndex. Second, we know that we can be called
        // for the same page multiple times. The condition of this while
        // loop acts as a check, ensuring that we don't attempt to do the
        // calculations again when we are called subsequent times for the
        // same page.
        while (last < pageIndex) {
            // if we are finished all columns in all rows
            if (row >= table.getRowCount() && col == 0) {
                return NO_SUCH_PAGE;
            }

            // rather than multiplying every row and column by the scale
            // factor
            // in findNextClip, just pass a width and height that have
            // already
            // been divided by it
            int scaledWidth = (int) (imgWidth / sf);
            int scaledHeight = (int) ((availableSpace - hclip.height) / sf);

            // calculate the area of the table to be printed for this page
            findNextClip(scaledWidth, scaledHeight);

            last++;
        }

        // create a copy of the graphics so we don't affect the one given to
        // us
        Graphics2D g2d = (Graphics2D) graphics.create();

        // translate into the co-ordinate system of the pageFormat
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        // to save and store the transform
        AffineTransform oldTrans;

        // if there's footer text, print it at the bottom of the imageable
        // area
        if (footerText != null) {
            oldTrans = g2d.getTransform();

            g2d.translate(0, imgHeight - footerTextSpace);

            String[] lines = footerText.split("\n");
            printText(g2d, lines, fRect, footerFont, imgWidth);

            g2d.setTransform(oldTrans);
        }

        // if there's header text, print it at the top of the imageable area
        // and then translate downwards
        if (headerText != null) {
            String[] lines = headerText.split("\n");
            printText(g2d, lines, hRect, headerFont, imgWidth);

            g2d.translate(0, headerTextSpace + H_F_SPACE);
        }

        // constrain the table output to the available space
        tempRect.x = 0;
        tempRect.y = 0;
        tempRect.width = imgWidth;
        tempRect.height = availableSpace;
        g2d.clip(tempRect);

        // if we have a scale factor, scale the graphics object to fit
        // the entire width
        if (sf != 1.0D) {
            g2d.scale(sf, sf);

            // otherwise, ensure that the current portion of the table is
            // centered horizontally
        } else {
            int diff = (imgWidth - clip.width) / 2;
            g2d.translate(diff, 0);
        }

        // store the old transform and clip for later restoration
        oldTrans = g2d.getTransform();
        Shape oldClip = g2d.getClip();

        // if there's a table header, print the current section and
        // then translate downwards
        if (header != null) {
            hclip.x = clip.x;
            hclip.width = clip.width;

            g2d.translate(-hclip.x, 0);
            g2d.clip(hclip);
            header.print(g2d);

            // restore the original transform and clip
            g2d.setTransform(oldTrans);
            g2d.setClip(oldClip);

            // translate downwards
            g2d.translate(0, hclip.height);
        }

        // print the current section of the table
        g2d.translate(-clip.x, -clip.y);
        g2d.clip(clip);
        table.print(g2d);

        // restore the original transform and clip
        g2d.setTransform(oldTrans);
        g2d.setClip(oldClip);

        // draw a box around the table
        g2d.setColor(Color.BLACK);
        g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);

        // dispose the graphics copy
        g2d.dispose();

        return PAGE_EXISTS;
    }

    private void printText(Graphics2D g2d, String[] lines, Rectangle2D rect, Font font, int imgWidth) {

        g2d.setColor(Color.BLACK);
        g2d.setFont(font);

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

            // if the text is small enough to fit, center it
            if (rect.getWidth() < imgWidth) {
                tx = (int) (imgWidth / 2 - g2d.getFontMetrics().getStringBounds(lines[i], g2d).getWidth() / 2);

                // otherwise, if the table is LTR, ensure the left side of
                // the text shows; the right can be clipped
            } else if (table.getComponentOrientation().isLeftToRight()) {
                tx = 0;

                // otherwise, ensure the right side of the text shows
            } else {
                tx = -(int) (Math.ceil(rect.getWidth()) - imgWidth);
            }

            int ty = (int) Math.ceil(Math.abs(rect.getY() + i * rect.getHeight() / lines.length));
            g2d.drawString(lines[i], tx, ty);
        }
    }

    private void findNextClip(int pw, int ph) {
        final boolean ltr = table.getComponentOrientation().isLeftToRight();

        // if we're ready to start a new set of rows
        if (col == 0) {
            if (ltr) {
                // adjust clip to the left of the first column
                clip.x = 0;
            } else {
                // adjust clip to the right of the first column
                clip.x = totalColWidth;
            }

            // adjust clip to the top of the next set of rows
            clip.y += clip.height;

            // adjust clip width and height to be zero
            clip.width = 0;
            clip.height = 0;

            // fit as many rows as possible, and at least one
            int rowCount = table.getRowCount();
            int rowHeight = table.getRowHeight(row);
            do {
                clip.height += rowHeight;

                if (++row >= rowCount) {
                    break;
                }

                rowHeight = table.getRowHeight(row);
            } while (clip.height + rowHeight <= ph);
        }

        // we can short-circuit for JTable.PrintMode.FIT_WIDTH since
        // we'll always fit all columns on the page
        if (printMode == JTable.PrintMode.FIT_WIDTH) {
            clip.x = 0;
            clip.width = totalColWidth;
            return;
        }

        if (ltr) {
            // adjust clip to the left of the next set of columns
            clip.x += clip.width;
        }

        // adjust clip width to be zero
        clip.width = 0;

        // fit as many columns as possible, and at least one
        int colCount = table.getColumnCount();
        int colWidth = colModel.getColumn(col).getWidth();
        do {
            clip.width += colWidth;
            if (!ltr) {
                clip.x -= colWidth;
            }

            if (++col >= colCount) {
                // reset col to 0 to indicate we're finished all columns
                col = 0;

                break;
            }

            colWidth = colModel.getColumn(col).getWidth();
        } while (clip.width + colWidth <= pw);

    }
}

But, like I said, when I click the "print" button, nothing happens. What could be going wrong?

Community
  • 1
  • 1
Vadio
  • 5
  • 2
  • 6
  • And when do you send the `Printable` to the printer? – MadProgrammer Oct 27 '14 at 23:26
  • Try calling `jTable2.print(JTable.PrintMode.NORMAL, header, null);` at the end of the method... – MadProgrammer Oct 27 '14 at 23:27
  • But, wouldn't this make the same thing as I was doing before? And at the end of the "TablePrintable" method, you say? Or after "return new TablePrintable"? I'm sortanew to those more advanced things, so I'm still slow to keep up... – Vadio Oct 27 '14 at 23:55
  • No, you've overridden the tables `getPrintable` method, which it uses when `print` is called, to print the table... – MadProgrammer Oct 27 '14 at 23:58
  • *"And at the end of the "TablePrintable" method, you say?"* - No, at the end of the `jButton4ActionPerformed` method – MadProgrammer Oct 27 '14 at 23:59
  • Oooh, I see. I tried putting it there, but it gives me an error, because the variable "header" doesn't exists. But, if I do set it again, I will end up with just 1 headline again, won't I? – Vadio Oct 28 '14 at 00:01
  • I have no idea, I thought that's what `TablePrintable` was suppose to solve wasn't it... – MadProgrammer Oct 28 '14 at 00:02
  • Well, I tried doing this, but in the end this was the result:imgur.com/tFjHWOh Maybe this was caused because I'm calling a custom printable method, and using the built-in method again? – Vadio Oct 28 '14 at 00:18

1 Answers1

2

With your newly modify JTable, you should only need to call it's print method.

DefaultTableModel dtm = new DefaultTableModel(new String[] { "Column 1" }, 1);
JTable jTable2 = new JTable(dtm) {
    @Override
    public Printable getPrintable(PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) {
        return new TablePrintable(this, printMode, headerFormat, footerFormat);
    }
};

try{
    jTable2.print(JTable.PrintMode.NORMAL, header, null);
}
catch(java.awt.print.PrinterException e){
    System.out.println("error");
}

Because you've overridden the getPrintable method to return your own implementation, this is what will be used to physically print the table...

Updated

The header text needs to be separated by a \n, for example...

MessageFormat header = new MessageFormat("Testing, 01\n02\n03");

Which can produce...

enter image description here

Updated

As near as I can tell, without been able to fully run the code, your print code should look something like...

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {

    Vector vetColuna = new Vector();
    Vector vetLinhas = new Vector();
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(str_conn, usuario, senha);
        stmt = con.createStatement();
        sql = "select topico, nota, datanota from notas where notas.cod_aluno =" + jTextField1.getText() + " and notas.cod_curso =" + jTextField2.getText() + " order by notas.datanota";
        rs = stmt.executeQuery(sql);
        if (rs == null) {
            return;
        }
        ResultSetMetaData rsmd;
        rsmd = rs.getMetaData();
        for (int i = 0; i < rsmd.getColumnCount(); i++) {
            vetColuna.add(rsmd.getColumnLabel(i + 1));
        }

        while (rs.next()) {
            Vector vetLinha = new Vector();
            for (int i = 0; i < rsmd.getColumnCount(); i++) {
                vetLinha.add(rs.getObject(i + 1));
            }
            vetLinhas.add(vetLinha);
        }
    } catch (ClassNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Erro\nNão foi possível carregar o driver.");
        System.out.println("Nao foi possivel carregar o driver");
        ex.printStackTrace();
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Erro\nCertifique-se de que todos os\ncampos estejam preenchidos corretamente.");
        System.out.println("Problema com o SQL");
        ex.printStackTrace();
    }

    MessageFormat header = new MessageFormat("Ficha Pedagógica - " + jComboBox1.getSelectedItem() + "\nNome do Aluno - " + jTextField1.getText());

    DefaultTableModel dtm = new DefaultTableModel(vetLinhas, vetColuna);
    JTable jTable2 = new JTable(dtm) {
        @Override
        public Printable getPrintable(PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) {
            return new TablePrintable(this, printMode, headerFormat, footerFormat);
        }
    };
    try {
        jTable2.setSize(jTable2.getPreferredSize());
        JTableHeader tableHeader = jTable2.getTableHeader();
        tableHeader.setSize(tableHeader.getPreferredSize());
        jTable2.print(JTable.PrintMode.FIT_WIDTH);
    } catch (PrinterException ex) {
        ex.printStackTrace();
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Well, I tried doing this, but in the end this was the result:http://imgur.com/tFjHWOh Maybe this was caused because I'm calling a custom printable method, and using the built-in method again? – Vadio Oct 28 '14 at 00:09
  • Seems to work fine for me, but you might like to have a look at [this question](http://stackoverflow.com/questions/26580954/how-to-print-selected-rows-jtable/26581137#26581137) for some ideas how to print an off screen table... – MadProgrammer Oct 28 '14 at 00:40
  • Well, but my question isn't really like this...I just want to know how to add two headlines in the print file. I was redirected to another topic, and then tried to use the code from there, but I had no sucess, so I came here and made this topic to try to get it working...but I'll take a look at it. Thanks for the help! – Vadio Oct 28 '14 at 00:43
  • You have an off screen table, they have an off screen table, neither will print properly, the answer is there. As to the multiline header, add a `\n` where ever you want a new line...simple – MadProgrammer Oct 28 '14 at 00:48
  • Well, now, that I added the content of the question you passed to me, it appear the box with the print options, but when I click "print", the file isn't created. And if I print directly from my printer, the result is the same as the image I sent above...(this one: http://imgur.com/tFjHWOh ). Here is my code: http://pastebin.com/PTyt0MzD – Vadio Oct 28 '14 at 20:30
  • Get rid of `JTable toPrint = new JTable(printModel);` and use `jTable2`, that's the table that's actually been printed. – MadProgrammer Oct 28 '14 at 20:43
  • I think I'm really dumb to not get this working... There are some problems: When I altered the code to this: http://pastebin.com/FdNcWYzf The print turned out like this: http://i.imgur.com/QkJq3AD.png And when I tried altering the code to this: http://pastebin.com/yKGXa4zi The print turned out like this: http://i.imgur.com/2xL42MU.png Also, the header isn't printing anymore. What am I doing wrong? – Vadio Oct 28 '14 at 21:07
  • You're doing something API wasn't designed to do, don't be surprised when it doesn't work ;) - Took me some time to figure it out to. Check update... – MadProgrammer Oct 28 '14 at 21:15
  • Well, I tried making the alterations, there was a thing I changed in the code - jTable2.setSize(toPrint.getPreferredSize()); because if I let it with "toPrint", it would give me a "symbol not found", so I changed "toPrint" to "jTable2", but this was the result: http://i.imgur.com/2xL42MU.png – Vadio Oct 28 '14 at 21:25
  • There's a rouge `jTable2.setModel(new DefaultTableModel(vetLinhas, vetColuna));` in your `resultset` gathering loop, which doesn't look good... – MadProgrammer Oct 28 '14 at 23:49
  • `DefaultTableModel dtm = new DefaultTableModel(new String[]{"Column 1"}, 1);` is the course of your current output... – MadProgrammer Oct 28 '14 at 23:52
  • I've updated the last example, but you seriously need to take the time to connect the various parts of the code together, you're just slapping stuff in there without consideration to how it's suppose to work together :{ – MadProgrammer Oct 28 '14 at 23:53
  • Right, so,I should remove my jTable2.setModel(new DefaultTableModel(vetLinhas, vetColuna)); ?And now I see that my DefaultTableModel dtm = new DefaultTableModel(new String[]{"Column 1"}, 1); is the output, but if I try to change this part of the code: (new String[]{"Column 1"}, 1); to (vetLinhas, vetColuna), so the table is printed just like it was printing before, it says "cannot find symbol" for both variables,I think because it's out of the "try" statement of the DataBase connection.But if I put it thee, then,"dtm",in this code: JTable jTable2 = new JTable(dtm), it says "can't find symbol" – Vadio Oct 29 '14 at 00:17
  • Ok, I'll check it, sorry D: – Vadio Oct 29 '14 at 00:18
  • Well, I don't know if this is because I'm a beginner dealing with a complex code (to me), I've made the alterations, and I'm reading and re-reading every line of code...I understand the connections between the variables and things used better now, but, while I did understand, I couldn't understand why it's not generating the file anymore...nor it's filling jTable2 anymore, after I removed the "jTable2.setModel(new DefaultTableModel(vetLinhas, vetColuna));" code. I understand that this code is now being used in "DefaultTableModel dtm = new DefaultTableModel(vetLinhas, vetColuna);", and that's – Vadio Oct 29 '14 at 00:41
  • why the variables "Vector vetColuna = new Vector(); and Vector vetLinhas = new Vector();" are outside of the "try", so they can be used outside of it, but I still don't know why it's not filling the table anymore. – Vadio Oct 29 '14 at 00:41
  • Relax, the code is a mess for both of us. I've updated the last code snippet, got rid of `toPrint`. Yes, the `Vector`s are outside the `try-catch` because we want to use them within the table model, which is used by `jTable2`... – MadProgrammer Oct 29 '14 at 00:44
  • Right, I'm up with you here. So, after I removed "jTable2.setModel(new DefaultTableModel(vetLinhas, vetColuna));" from inside the "try-catch", the jTable2 didn't fill anymore. I tought that was why this line of code exists: "DefaultTableModel dtm = new DefaultTableModel(vetLinhas, vetColuna);", so it would do the same thing as the line of code inside of the "try-catch", right? – Vadio Oct 29 '14 at 00:56
  • Yes, kind of. Basically, you're waiting until the two Vectors are filled with data before creating the model and applying it to the table. It's more optimised this way ... and less confusing... – MadProgrammer Oct 29 '14 at 01:00
  • Ok, got it. So, the following code after this, would be the act of actually printing the table, right? And the file isn't created because the table is empty when this happens. I'm starting to understand. I just can't understand why the table isn't begin filled, because the SQL code is working fine, so the Vectors are supposed to be filled with the data. The way of setting the collected data to the table changed a little, but it should produce the same results... – Vadio Oct 29 '14 at 01:04
  • Based on the updated snippet, yes, the table should be getting filled with data. You could use `System.out.println(jTable2.getRowCount());` to verify the row count of the table after you've created it... – MadProgrammer Oct 29 '14 at 01:07
  • Well, I did that, and the number of rows of the table is right: 11 (because there are 11 registers on my database), so technically it would be filled, but even if it says that there are 11 rows, the table is still empty. If I try putting DefaultTableModel dtm = new DefaultTableModel(vetLinhas, vetColuna); inside the "try-catch" statement, the JTable jTable2 = new JTable(dtm) {...} line of code says that there's an error, and underlines "dtm" (cannot get symbol). I thought that putting it into there would work, because the old code jTable2.setModel(new DefaultTableModel(vetLinhas, vetColuna)); – Vadio Oct 29 '14 at 17:11
  • was filling the table. So I don't really know, because, if I leave that code there, it fills the table, but the printed page doesn't appear in my computer. (Because the table would technically be empty, I think?) – Vadio Oct 29 '14 at 17:12
  • Well, I've noticed something: jTable2.setModel(new DefaultTableModel(vetLinhas, vetColuna)); fills the table because it's using "setModel". The code DefaultTableModel dtm = new DefaultTableModel(vetLinhas, vetColuna); isn't setting the model of the table, so it's not filling it with the contents of vetLinhas and vetColuna. Is that right? Because the rest of the code isn't setting anything, just getting the size of headers and getting rows... – Vadio Oct 29 '14 at 18:41
  • Wow, wow, I got something to appear on the page. Just asking, why is the parameter of this line of code: DefaultTableModel printModel = new DefaultTableModel(0, viewModel.getColumnCount()); why is it like this? I mean, what does 0 means? Because when I changed the 0 to "viewModel.getRowCount", I could print the page and got this to appear: http://i.imgur.com/cDLQZps.png and look at it, it has 3 columns and 11 rows! But I just don't know why it isn't getting the data. Is it because I didn't set the jTable2 format like I was doing before? – Vadio Oct 29 '14 at 18:44
  • I tried putting jTable2.setModel(new DefaultTableModel(vetLinhas, vetColuna)); just before of DefaultTableModel dtm = new DefaultTableModel(vetLinhas, vetColuna); but, while the contents did appear at the table, the page stayed like this again: http://i.imgur.com/cDLQZps.png – Vadio Oct 29 '14 at 18:46
  • Curious thing: the header isn't printing anymore, just noticed this. – Vadio Oct 29 '14 at 18:52
  • Regarding the header, I tried to change this line of code: toPrint.print(JTable.PrintMode.FIT_WIDTH); to this: toPrint.print(JTable.PrintMode.FIT_WIDTH, header,null); because there were no errors, but the parameters headerFormat, footerFormat were missing, but the result was this: http://i.imgur.com/Oz2yNnm.png the header didn't break the line. – Vadio Oct 29 '14 at 18:54
  • I got it to print the table! But it's a little messy...the table is much smaller than before, and the header still doesn't prints right....here is the code: http://pastebin.com/Esq23Qv6 I changed this part: DefaultTableModel printModel = new DefaultTableModel(vetLinhas, vetColuna); it was like this before: DefaultTableModel printModel = new DefaultTableModel(viewModel.getRowCount(), viewModel.getColumnCount()); And here is the image: http://i.imgur.com/P9awvB0.png – Vadio Oct 29 '14 at 19:11
  • I got it to print the 2 headers! But the table still looks small. I left my code commented, and decide to use the code provided in your answer, changing this line: jTable2.print(JTable.PrintMode.FIT_WIDTH,header,null); But what should I do to resize the table in the page? Here is the image of the current progress: http://i.imgur.com/sunKHVK.png – Vadio Oct 29 '14 at 19:22
  • I'm guessing that the answer lies within the class "TablePrintable", so do I need to change some parameters of colWidth there to make it work? I can't guess this one... – Vadio Oct 29 '14 at 19:32
  • I found a code to resize the columns to the size of the contents automatically. But, the table is still small...is there a way to scale it to fit the page? Here is the image of how it's looking like: http://i.imgur.com/14wRELT.png even if I change the font size on the table properties, the result is always the table with this size. – Vadio Oct 29 '14 at 20:57
  • Try using PrintMode.NORMAL rather then PrintMode.FIT_WIDTH – MadProgrammer Oct 29 '14 at 21:03
  • I've already tried this, but it won't work. Well, I added some more code, so I'll post all my code here: http://pastebin.com/Dv4J8x7Y the class "ColumnsAutoSizer" is used here: ColumnsAutoSizer.sizeColumnsToFit(jTable2); so it can resize the Columns of the table. But even if I use PrintMode.NORMAL, the table doesn't fills the page...it keeps small. Even changing the size of the font in the table properties didn't work... – Vadio Oct 29 '14 at 21:17
  • Just a question: in the last "try-catch", there's this line of code: jTable2.setSize(jTable2.getPreferredSize()); what does it do? It looks like to me it's setting the size of jTable2, but, what does this "getPreferredSize" means? Maybe it's this that is making the table so small? – Vadio Oct 29 '14 at 21:45
  • Right. Well, I think I've run out of ideas to how I can make the table fit the page...I've looked everywhere I could on google, but I haven't found the solution...should I start another question regarding only the size of the table? – Vadio Oct 29 '14 at 22:01
  • My quick test doesn't seem to make a difference between NORMAL or FIT – MadProgrammer Oct 29 '14 at 23:49
  • Yes, that's what I said, even if I use FIT_WIDTH or NORMAL, the size of the table/font stays the same...I just want the table to "fit" to the size of the page, with a little more larger font. But even if I change the font size of the table, it doesn't reflects on the page. – Vadio Oct 30 '14 at 15:05
  • Well, I think I'll begin another question, specific to the table size problem. I'm very grateful to you, sir, you've been really patient and helped me a lot (I think that I got so lost because I'm still a beginner, so this was advanced stuff to me...). This will help anyone with the same problem. Well, many thanks!!! I've marked your answer as "accepted" :D – Vadio Oct 30 '14 at 15:44
  • Yeah, FIT_WIDTH is used to shrink the table not expand it. With the column sizes restricted, you'll probably never get it to expand the full width – MadProgrammer Oct 30 '14 at 18:46
  • Hmmm, yeah, but even with "NORMAL", the result is the same...and the size of my jTable in the Frame is big. But that doesn't seems to affect the printed table. – Vadio Oct 30 '14 at 19:37
  • Yep, NORMAL uses the tables actual size, FIT_WIDTH scales the table down to fit, not up – MadProgrammer Oct 30 '14 at 19:46
  • Yes, I understand this, but what I am trying to say is that, regardless of the size of my table in the frame, and regardless if I use "NORMAL" or "FIT_WIDTH", the printed table is always at the same size. Maybe it's something related to the custom print code? – Vadio Oct 30 '14 at 19:49