Solved

copy multiple rows in JTable

Posted on 2003-10-21
8
1,158 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
  • 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
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 20 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 15

Accepted Solution

by:
jimmack earned 30 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

863 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now