?
Solved

copy multiple rows in JTable

Posted on 2003-10-21
8
Medium Priority
?
1,306 Views
Last Modified: 2007-12-19
I am using DefaultTableModel and I am trying to copy selected rows from JTable and insert them below the rows I selected.  

For example, when I select  2 rows which contain different data, my JTable displays the first row twice after the copy event happened.  I know my insertRow statement is not correct, please help.  Thanks!!

------------------------
void menuCopyRecords_actionPerformed(ActionEvent e)
{
  int selectedRows = myEntriesTable.getSelectedRows();  //JTable myEntriesTable

  Vector data = defaultTableModel.getDataVector();
 
  for (int i = 0; i < selectedRows.length; i++)
  {
     Vector targetRows = (Vector) data.elementAt(selectedRows[i]);

     defaultTableModel.insertRow(selectedRows[i] + 1,  targetRows);  
     defaultTableModel.fireTableDataChanged();
   }
}

0
Comment
Question by:fcwEx
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 7

Expert Comment

by:tomboshell
ID: 9597132
I see some quick problems:
 int selectedRows = myEntriesTable.getSelectedRows();  //JTable myEntriesTable
should be an array
 int[] selectedRows = myEntriesTable.getSelectedRows();  //JTable myEntriesTable

and you said that you wanted the copied data 'before' the rows I selected the following line would place it 'after', so you should decrement the location and not increment
defaultTableModel.insertRow(selectedRows[i] + 1,  targetRows);  
would then be
defaultTableModel.insertRow(selectedRows[i] - 1,  targetRows);  

That will give you two copies of defined rows.  
0
 
LVL 37

Expert Comment

by:zzynx
ID: 9597306
To be sure I understand what you want
ex.
Table contains:

Row 1
Row 2
Row 3
Row 4
Row 5

You select Row 2 and Row 4 and press the button.
What do you want to see? This?

Row 1
Row 2
Copy of Row 2
Row 3
Row 4
Copy of Row 4
Row 5
0
 
LVL 37

Expert Comment

by:zzynx
ID: 9597406
If the above is what you want try this:

[I suppose the variable defaultTableModel equals myEntriesTable.getModel() ]

void menuCopyRecords_actionPerformed(ActionEvent e)
{
  int selectedRows = myEntriesTable.getSelectedRows();

  Vector data = defaultTableModel.getDataVector();
 
  for (int i = selectedRows.length-1; i >=0 ; i--)  //---- from end to start
  {
     Vector targetRows = (Vector) data.elementAt(selectedRows[i]);

     defaultTableModel.insertRow(selectedRows[i] + 1,  targetRows);
     //----- Be more specific, so nothing more than needed is updated:
     defaultTableModel.fireTableRowsInserted(selectedRows[i] + 1, selectedRows[i] + 1);
   }
}

My main point is that I changed the for-loop to start from the 'end'.

That's a common point of interest: when changing a table/list always start from the end so that your previously got index-information (in your case: selectedRows) stays valid.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 80 total points
ID: 9597430
Here's the complete code you can play with:

import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;

public class SimpleTableDemo extends JFrame {
    private boolean DEBUG = true;
    private JTable table;
    private DefaultTableModel defaultTableModel;

    public SimpleTableDemo() {
        super("SimpleTableDemo");

        Object[][] data = {
            {"Mary", "Campione",
             "Snowboarding", new Integer(5), new Boolean(false)},
            {"Alison", "Huml",
             "Rowing", new Integer(3), new Boolean(true)},
            {"Kathy", "Walrath",
             "Chasing toddlers", new Integer(2), new Boolean(false)},
            {"Sharon", "Zakhour",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Angela", "Lih",
             "Teaching high school", new Integer(4), new Boolean(false)}
        };

        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};

        defaultTableModel = new DefaultTableModel(data, columnNames);
        table = new JTable(defaultTableModel);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));

        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    printDebugData(table);
                }
            });
        }

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this window.
        getContentPane().add(scrollPane, BorderLayout.CENTER);
       
        JButton button = new JButton("Copy");
        button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }
        });
       
        getContentPane().add(button, BorderLayout.SOUTH);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

   private void copyButtonActionPerformed(java.awt.event.ActionEvent evt) {
      int selectedRows[] = table.getSelectedRows();

      Vector data = defaultTableModel.getDataVector();

      for (int i = selectedRows.length-1; i >=0; i--)
      {
         Vector targetRows = (Vector) data.elementAt(selectedRows[i]);

         defaultTableModel.insertRow(selectedRows[i] + 1,  targetRows);
         defaultTableModel.fireTableRowsInserted(selectedRows[i] + 1, selectedRows[i] + 1);
      }
    }
   
    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();

        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            }
            System.out.println();
        }
        System.out.println("--------------------------");
    }

    public static void main(String[] args) {
        SimpleTableDemo frame = new SimpleTableDemo();
        frame.pack();
        frame.setVisible(true);
    }
}
0
 
LVL 15

Accepted Solution

by:
jimmack earned 120 total points
ID: 9597436
Hmm.  A little clarification is definitely in order.

First, tomboshell.  I think you misread the question.  fcwEx used the word "below", not "before".

zzynx raises a good point too.  Is the table set up to allow non-contiguous (MULTIPLE_INTERVAL_SELECTION) selections (because this will really confuse the issue ;-))

May I propose:

void menuCopyRecords_actionPerformed(ActionEvent e)
{
  int[] selectedRows = myEntriesTable.getSelectedRows();  //JTable myEntriesTable

  if (selectedRows.length > 0)
  {
    Vector data = defaultTableModel.getDataVector();

    int insertPoint = selectedRows[selectedRows.length - 1] + 1;
 
    for (int i = 0; i < selectedRows.length; i++)
    {
       Vector targetRow = (Vector) data.elementAt(selectedRows[i]);

       defaultTableModel.insertRow(insertPoint,  targetRow);
       insertPoint++;
    }

    defaultTableModel.fireTableDataChanged();
  }
}

This should take care of non-contiguous selections and will only try to do the copying if you have selected at least one row.  Also, the table need only be redrawn when all the copies have been made.
0
 
LVL 7

Expert Comment

by:tomboshell
ID: 9597708
Yep, I guess I did misread
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9597750
Must be something psychological about the context or the position on the screen, but to start with, I read it as "before" as well ;-)
0
 

Author Comment

by:fcwEx
ID: 9604634
Thanks all for the help!!
0

Featured Post

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month10 days, 20 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question