Solved

copy multiple rows in JTable

Posted on 2003-10-21
8
1,255 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 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
 
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How do I remove an object from a 3 60
Java Restore security prompts not working 10 250
ejb mdb examples 1 38
junit as external jar or library 7 58
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…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This video teaches viewers about errors in exception handling.
Suggested Courses

734 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