Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / June 2005

Tip: Looking for answers? Try searching our database.

JTables

Thread view: 
freesoft_2000@yahoo.com - 22 Jun 2005 20:58 GMT
Hi everyone,

            I am currently trying to print a multipage JTable but the
the thing is on the left hand side of the JTable does not have any grid
lines and i have tried to draw a rectangle around the jTable before
printing it but nothing is happening.

           Another thing is that when the JTable goes on the next page
for printing there are trailing grid lines on the previous page. I have
tried clipping and translating it but nothing works.

          You guys can try removing the painting of the Table Headers
to get a clearer picture if you want

Here is the code with a mini test program so you guys can run the
program and see what i mean

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.awt.print.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.imageio.*;

public class JTables2 implements ActionListener

{

    JFrame fr = new JFrame ("Frame");

    JButton Button12 = new JButton("Print");

    DefaultTableModel TableModel1 = new DefaultTableModel(20, 30);

    //The below command line sets the table model to the JTable

    JTable Table1 = new JTable(TableModel1);

    JScrollPane ScrollPane1 = new JScrollPane(Table1,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

    Dimension Size1 = new Dimension();

    PrinterJob prnJob;
    PageFormat format;

    public void initialize ()
    {
        Container pane = fr.getContentPane();
        pane.setLayout(new FlowLayout());
        fr.setSize(250,300);
        fr.setLocation(300,300);
        fr.setBackground(Color.lightGray);
        //The below command line must be set to false so that user
        //resizing is allowed

        Table1.setAutoCreateColumnsFromModel(false);
        Size1.width = 350;
        Size1.height = 250;
        ScrollPane1.setPreferredSize(Size1);
        Table1.setModel(TableModel1);
        Table1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        Table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        pane.add(ScrollPane1);
        pane.add(Button12);

        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Button12.addActionListener(this);
        fr.pack();
        fr.setVisible(true);
    }

    public void printData ()
    {
        //This function prints the contents of the JTable

        StyledTextTableRenderer2 StyledTextTableRenderer1 = new
StyledTextTableRenderer2();
        StyledTextTableRenderer1.settable(Table1);

        try
        {
            //The below command line gets the printer job

            prnJob = PrinterJob.getPrinterJob();

            if(format == null)
            {
                format = prnJob.defaultPage();
            }

            //The below command line sets the printable interface and the
            //format for the page to be printed

            prnJob.setPrintable(StyledTextTableRenderer1, format);

            //The below command line calls the native print dialog

            if(prnJob.printDialog() == false)
            {
                return;
            }

            //The below command line prints out the document if the user clicked
Ok

            prnJob.print();
        }

        catch (PrinterException e)
        {

        }

    }

    public void actionPerformed(ActionEvent event)
    {
        JComponent b = (JComponent)event.getSource();

        if(b == Button12)
        {
            printData();
            fr.repaint();
        }

    }

    public static void main(String args[])
    {
        JTables2 a = new JTables2();
        a.initialize();
    }
}

class StyledTextTableRenderer2 implements Printable
{
    JTable Table1 = new JTable();

    public int print(Graphics g, PageFormat pageFormat, int pageIndex)
throws PrinterException
    {

        Graphics2D  g2 = (Graphics2D) g;
        g2.setColor(Color.black);

        int fontHeight = g2.getFontMetrics().getHeight();
        int fontDesent = g2.getFontMetrics().getDescent();

        //leave room for page number

        double pageHeight = pageFormat.getImageableHeight() - fontHeight;
        double pageWidth = pageFormat.getImageableWidth();

        double tableWidth =
(double)Table1.getColumnModel().getTotalColumnWidth();

        double headerHeightOnPage = Table1.getTableHeader().getHeight();
        double tableWidthOnPage = tableWidth;

        double oneRowHeight = (Table1.getRowHeight()+ Table1.getRowMargin());
        int numRowsOnAPage = (int)((pageHeight-headerHeightOnPage)/
oneRowHeight);
        double pageHeightForTable = oneRowHeight * numRowsOnAPage;
        int totalNumPages=
(int)Math.ceil(((double)Table1.getRowCount())/numRowsOnAPage);

        if(pageIndex>=totalNumPages)
        {
            Table1.setShowGrid(true);

            return NO_SUCH_PAGE;
        }

        g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        //bottom center

        g2.drawString("Page "+ (pageIndex+1), (int)pageWidth/2-35,
(int)(pageHeight
        + fontHeight-fontDesent));

        g2.translate(0f,headerHeightOnPage);
        g2.translate(0f,-pageIndex * pageHeightForTable);

        //If this piece of the table is smaller
        //than the size available,
        //clip to the appropriate bounds.

        if(pageIndex + 1 == totalNumPages)
        {
            int lastRowPrinted = numRowsOnAPage * pageIndex;
            int numRowsLeft = Table1.getRowCount() - lastRowPrinted;
            g2.setClip(0,(int)(pageHeightForTable * pageIndex), (int)
Math.ceil(tableWidthOnPage),
            (int)Math.ceil(oneRowHeight * numRowsLeft));
        }

        //else clip to the entire area available

        else
        {
            g2.setClip(0, (int)(pageHeightForTable*pageIndex), (int)
Math.ceil(tableWidthOnPage),
            (int) Math.ceil(pageHeightForTable));
        }
//This is where i try to draw the rectangle around
//the JTable
        g2.drawRect(0,(int)headerHeightOnPage,(int)tableWidthOnPage,
(int)((pageHeightForTable)* Table1.getRowCount()));

        Table1.paint(g2);
        g2.translate(0f, pageIndex * pageHeightForTable);
        g2.translate(0f, -headerHeightOnPage);
        g2.setClip(0, 0,
(int)Math.ceil(tableWidthOnPage),(int)Math.ceil(headerHeightOnPage));
        Table1.getTableHeader().paint(g2);
        //paint header at top

        /*
g2.translate(0f, pageIndex * pageHeightForTable);
g2.setColor(Color.gray);
g2.drawRect(0,0,(int)tableWidthOnPage, (int)((pageHeightForTable)*
Table1.getRowCount()));
*/
        System.out.println("" + pageHeightForTable);

        return Printable.PAGE_EXISTS;
    }

    public void settable(JTable table)
    {
        //This function gets the JTable and its table model

        Table1 = table;
        Table1.setShowGrid(false);
    }

}

     Basically i am trying to print a JTable with the option of table
headers as a complete grid and withou any trainling lines

               I know that 1.5 now has printing but i need to use this
way of printing(i.e. by using the printable interface) for the program
to suit a special kind of need

Any help is greatly appreciated

Thank You

Yous Sincerely

Richard West
Liz - 23 Jun 2005 23:24 GMT
I have spend days to make the JTable printing to work. I have faced lot
of issues similar to yours. Finally I end up using free QuickTable java
component (http://quicktable.org) which is an implementation on top of
JTable. QuickTable has simplified printing by one line methods.

For printing
quiktable.print()

For printpreview (screen shot:
http://quicktable.org/images/printpreview.jpg)
quiktable.printPreview()

To get the printable object
java.awt.print.Printable prn = quicktable.getPrintable(PrintProperties
prop)

As you needed, it can optionally print a rectangle border around. It
can split the long tables into multiple pages.

Screenshots of other features can be found here.
http://quicktable.org/screenshots.htm
Christian Kaufhold - 27 Jun 2005 21:15 GMT
>             I am currently trying to print a multipage JTable but the
> the thing is on the left hand side of the JTable does not have any grid
> lines and i have tried to draw a rectangle around the jTable before
> printing it but nothing is happening.

Try painting afterwards, so it is not erased again, or really outside the
table. (Also use the grid color?)

>            Another thing is that when the JTable goes on the next page
> for printing there are trailing grid lines on the previous page. I have
> tried clipping and translating it but nothing works.

rowMargin is already included in the rowHeight; this is wrong:

>                double oneRowHeight = (Table1.getRowHeight()+ Table1.getRowMargin());

>                Table1.paint(g2);

Should you not use "print" here? (Does it matter?)

CHristian


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.