Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

imagehttp://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
N?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
Certifique-se de que todos os
campos 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("
").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("
");
            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("
");
            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;
        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
119 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 , for example...

MessageFormat header = new MessageFormat("Testing, 01
02
03");

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
N?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
Certifique-se de que todos os
campos estejam preenchidos corretamente.");
        System.out.println("Problema com o SQL");
        ex.printStackTrace();
    }

    MessageFormat header = new MessageFormat("Ficha Pedagógica - " + jComboBox1.getSelectedItem() + "
Nome 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();
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...