Copy data of one JTable to another. - Java Swing

Java examples for Swing:JTable

Description

Copy data of one JTable to another.

Demo Code


//package com.java2s;

import javax.swing.JTable;

import javax.swing.table.DefaultTableModel;

public class Main {
    /**/* ww  w . j a  va 2  s.co  m*/
     * Copy data of one table to another. If no destination table is given
     * as argument, a new table with a DefaultTableModel is created.
     *
     * The destination table should have a table model that is at least
     * a DefaultTableModel (or derived).
     *
     * @param source
     * @param destination
     * @return Destination table
     */
    public static JTable copyTableData(JTable source, JTable destination,
            int startCol) {

        int cols = source.getColumnCount();
        int rows = source.getRowCount();
        Object[][] o = new Object[rows][cols];

        if (destination == null) {
            destination = new JTable(new DefaultTableModel(
                    source.getRowCount(), source.getColumnCount()));
        }

        for (int row = 0; row < rows; row++) {

            for (int column = 0 + startCol; column < cols; column++) {
                o[row][column] = source.getValueAt(row, column);
            }

            setTableRow(destination, row, o[row]);

        }

        return destination;

    }

    /**
     * Add a row with data in a table. When the row does not exist, a new
     * row is created using DefaultTableModel.addRow.
     *
     * @param table
     * @param row
     * @param data
     */
    public static void setTableRow(JTable table, int row, Object[] data) {

        if (table.getRowCount() - 1 >= row) {

            for (int column = 0; column < table.getColumnCount(); column++) {
                table.setValueAt(data[column], row, column);
            }

        } else {
            ((DefaultTableModel) table.getModel()).addRow(data);
        }

    }
}

Related Tutorials