Solved

copy multiple rows in JTable

Posted on 2003-10-21
8
1,138 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 15

Accepted Solution

by:
jimmack earned 30 total points
Comment Utility
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
Comment Utility
Yep, I guess I did misread
0
 
LVL 15

Expert Comment

by:jimmack
Comment Utility
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
Comment Utility
Thanks all for the help!!
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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 third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

771 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

12 Experts available now in Live!

Get 1:1 Help Now