CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Sep 2011
    Posts
    4

    Question How can I copy the headers along with the table data in a JTable?

    I want to change the following code so that when I press ctrl-a it copies not only the table data but also the header text. How do I do this? Please respond with working code example if you can.

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.JTableHeader;

    public class JTableTest {

    String data[][] = { { "Name1", "Surname1", "Note1", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" },
    { "Name2", "Surname2", "Note2", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" },
    { "Name3", "Surname3", "Note3", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" },
    { "Name4", "Surname4", "Note4", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" } };
    String header[] = { "Name", "Surname", "Note", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" };
    static JScrollPane pane;
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    public JTableTest(String title) {
    JFrame frame = null;
    frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(true);

    JPanel resultPanel = new JPanel(new BorderLayout());
    resultPanel.setOpaque(true);
    final JTable table = new JTable(data, header) {
    private static final long serialVersionUID = 1L;

    public Dimension getMaximumSize() {
    setMaximumSize(new Dimension(screenSize.width/4, screenSize.height/4));
    setMinimumSize(getPreferredScrollableViewportSize());
    return getPreferredSize();
    }
    };
    table.setFillsViewportHeight(true);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    JTableHeader header = table.getTableHeader();
    header.setEnabled(true);
    table.setAutoscrolls(true);
    table.setDragEnabled(true);
    table.setAutoCreateRowSorter(true);
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionInterval(0, 0);
    table.setTableHeader(header);

    pane = new JScrollPane(table);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    pane.setAutoscrolls(true);
    pane.setColumnHeaderView(header);
    pane.setRowHeaderView(header);
    pane.setWheelScrollingEnabled(true);
    resultPanel.add(pane);
    resultPanel.setAutoscrolls(true);

    frame.setContentPane(resultPanel);
    frame.setSize(500, 200);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    }

    /**
    * @param args
    */
    public static void main(String[] args) {
    new JTableTest( "JTable Test" );

    }

    }

  2. #2
    Join Date
    Sep 2011
    Posts
    4

    Re: How can I copy the headers along with the table data in a JTable?

    Sorry for the unformatted code in the initial posting.

    Code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.JTableHeader;
    
    public class JTableTest {
    
    	String data[][] = { { "Name1", "Surname1", "Note1", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" },
    						{ "Name2", "Surname2", "Note2", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" },
    						{ "Name3", "Surname3", "Note3", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" },
    						{ "Name4", "Surname4", "Note4", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" } };
    	String header[] = { "Name", "Surname", "Note", "Datapoint1", "Datapoint2", "Datapoint3", "Datapoint4", "Datapoint5" };
    	static JScrollPane pane;
    	final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    
    	public JTableTest(String title) {
    		JFrame frame = null;
    		frame = new JFrame(title);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setResizable(true);
    
    		JPanel resultPanel = new JPanel(new BorderLayout());
    		resultPanel.setOpaque(true);
    		final JTable table = new JTable(data, header) {
    			private static final long serialVersionUID = 1L;
    
    			public Dimension getMaximumSize() {
    				setMaximumSize(new Dimension(screenSize.width/4, screenSize.height/4));
    				setMinimumSize(getPreferredScrollableViewportSize());
    				return getPreferredSize();
    			}
    		};
    		table.setFillsViewportHeight(true);
    		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    		JTableHeader header = table.getTableHeader();
    		header.setEnabled(true);
    		table.setAutoscrolls(true);
    		table.setDragEnabled(true);
    		table.setAutoCreateRowSorter(true);
    		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    		table.setColumnSelectionAllowed(true);
    		table.setRowSelectionAllowed(true);
    		table.setColumnSelectionInterval(0, 0);
    		table.setTableHeader(header);
    
    		pane = new JScrollPane(table);
    		pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    		pane.setAutoscrolls(true);
    		pane.setColumnHeaderView(header);
    		pane.setRowHeaderView(header);
    		pane.setWheelScrollingEnabled(true);
    		resultPanel.add(pane);
    		resultPanel.setAutoscrolls(true);
    
    		frame.setContentPane(resultPanel);
    		frame.setSize(500, 200);
    		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		frame.pack();
    		frame.setVisible(true);
    }
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    	    new JTableTest( "JTable Test" );
    
    	}
    
    }

  3. #3
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: How can I copy the headers along with the table data in a JTable?

    Can you clearly explain what you are trying to do and which bit you are stuck on.

    For instance:
    Where do you want to copy the information to (if it's the clipboad see this article)?
    Do you know how to add a key listener (if not see this tutorial)

    It's unlikely anyone is going to write it for you but we will try to help you to write it for yourself.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  4. #4
    Join Date
    Sep 2011
    Posts
    4

    Re: How can I copy the headers along with the table data in a JTable?

    The problem is that when I try to copy all of the info in the JTable, all I get is the data and not the headers.

    What I get when I copy the data is:
    Code:
    Name1	Surname1	Note1	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    Name2	Surname2	Note2	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    Name3	Surname3	Note3	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    Name4	Surname4	Note4	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    What I want is to include the header row:
    Code:
    NAME    SURNAME         NOTE    DATAPOINT1      DATAPOINT2      DATAPOINT3      DATAPOINT4      DATAPOINT5
    Name1	Surname1	Note1	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    Name2	Surname2	Note2	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    Name3	Surname3	Note3	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    Name4	Surname4	Note4	Datapoint1	Datapoint2	Datapoint3	Datapoint4	Datapoint5
    Please let me know if you need more information. Thanks.

  5. #5
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: How can I copy the headers along with the table data in a JTable?

    Can you post the code you are using to do the copy.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  6. #6
    Join Date
    Sep 2011
    Posts
    4

    Re: How can I copy the headers along with the table data in a JTable?

    I just run the code I showed, click on the JTable, press ctrl-a then ctrl-c. The data it copies only has the data and not the headers.
    There is no other code I run and I do not know how to get a copy of the data to include the headers.

  7. #7
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: How can I copy the headers along with the table data in a JTable?

    Ok. But that's not what you said in your first post, you said you were doing a copy using CTRL+A.
    CTRL+A and CTRL+C are actions built into JTable. The first one does a select all and the second one does the copy.

    As far as I know you have 2 choices here. You either replace the standard transfer handler with one of your own that also appends the header data or write your own action and handle the copy to the clipboard yourself.

    The easiest is to replace the transfer handler. The standard transfer handler is:

    Code:
        static class TableTransferHandler extends TransferHandler implements UIResource {
    
    	/**
    	 * Create a Transferable to use as the source for a data transfer.
    	 *
    	 * @param c  The component holding the data to be transfered.  This
    	 *  argument is provided to enable sharing of TransferHandlers by
    	 *  multiple components.
    	 * @return  The representation of the data to be transfered.
    	 *
    	 */
            protected Transferable createTransferable(JComponent c) {
    	    if (c instanceof JTable) {
    		JTable table = (JTable) c;
    		int[] rows;
    		int[] cols;
    		
    		if (!table.getRowSelectionAllowed() && !table.getColumnSelectionAllowed()) {
    		    return null;
    		}
    		
                    if (!table.getRowSelectionAllowed()) {
                        int rowCount = table.getRowCount();
    
                        rows = new int[rowCount];
                        for (int counter = 0; counter < rowCount; counter++) {
                            rows[counter] = counter;
                        }
                    } else {
    		    rows = table.getSelectedRows();
    		}
    		
                    if (!table.getColumnSelectionAllowed()) {
                        int colCount = table.getColumnCount();
    
                        cols = new int[colCount];
                        for (int counter = 0; counter < colCount; counter++) {
                            cols[counter] = counter;
                        }
                    } else {
    		    cols = table.getSelectedColumns();
    		}
                    
    		if (rows == null || cols == null || rows.length == 0 || cols.length == 0) {
    		    return null;
    		}
                    
                    StringBuffer plainBuf = new StringBuffer();
                    StringBuffer htmlBuf = new StringBuffer();
                    
                    htmlBuf.append("<html>\n<body>\n<table>\n");
                    
                    for (int row = 0; row < rows.length; row++) {
                        htmlBuf.append("<tr>\n");
                        for (int col = 0; col < cols.length; col++) {
                            Object obj = table.getValueAt(rows[row], cols[col]);
                            String val = ((obj == null) ? "" : obj.toString());
                            plainBuf.append(val + "\t");
                            htmlBuf.append("  <td>" + val + "</td>\n");
                        }
                        // we want a newline at the end of each line and not a tab
                        plainBuf.deleteCharAt(plainBuf.length() - 1).append("\n");
                        htmlBuf.append("</tr>\n");
                    }
    
                    // remove the last newline
                    plainBuf.deleteCharAt(plainBuf.length() - 1);
                    htmlBuf.append("</table>\n</body>\n</html>");
                    
                    return new BasicTransferable(plainBuf.toString(), htmlBuf.toString());
    	    }
    
    	    return null;
    	}
    
            public int getSourceActions(JComponent c) {
    	    return COPY;
    	}
    }
    You need to create your own transfer handler based on the above and rewrite the createTransferable(..) method to also get the data from the header for the selected columns. Notice how it creates 2 different versions of the copied data, one as html and one as tab separated plain text. The component the data is pasted into can select which is the most appropriate format for it to use.

    Finally call the table's setTransferHandler(..) method to tell the table to use your custom handler.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured