Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

copy multiple rows in JTable

Posted on 2003-10-21
8
Medium Priority
?
1,354 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

610 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