/** * This method is activated on the Keystrokes we are listening to in this implementation. Here it * listens for Copy and Paste ActionCommands. Selections comprising non-adjacent cells result in * invalid selection and then copy action cannot be performed. Paste is done by aligning the upper * left corner of the selection with the 1st element in the current selection of the JTable. * * @param e */ public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuffer sbf = new StringBuffer(); // Check to ensure we have selected only a continguous block of cells int numcols = jTable1.getSelectedColumnCount(); int numrows = jTable1.getSelectedRowCount(); int[] rowsselected = jTable1.getSelectedRows(); int[] colsselected = jTable1.getSelectedColumns(); if (rowsselected.length == 0 || colsselected.length == 0) { AppUtility.msgError(frame, "You have to select cells to copy !!"); return; } String temp = ""; for (int l = 0; l < numrows; l++) { for (int m = 0; m < numcols; m++) { if (jTable1.getValueAt(rowsselected[l], colsselected[m]) != null) { sbf.append(jTable1.getValueAt(rowsselected[l], colsselected[m])); } else { sbf.append(""); } if (m < numcols - 1) { sbf.append("\t"); } } sbf.append("\n"); stsel = new StringSelection(sbf.toString()); system = Toolkit.getDefaultToolkit().getSystemClipboard(); system.setContents(stsel, stsel); } } if (e.getActionCommand().compareTo("Paste") == 0) { jTable1 .getParent() .getParent() .getParent() .setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); String table = ""; if (debug) { System.out.println("Trying to Paste"); } int startRow = 0; // (jTable1.getSelectedRows())[0]; int startCol = 0; // (jTable1.getSelectedColumns())[0]; while (jTable1.getRowCount() > 0) { ((DefaultTableModel) jTable1.getModel()).removeRow(0); } try { String trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor)); if (debug) { System.out.println("String is: " + trstring); } StringTokenizer st1 = new StringTokenizer(trstring, "\n"); if (insertRowsWhenPasting) { for (int i = 0; i < st1.countTokens(); i++) { ((DefaultTableModel) jTable1.getModel()).addRow(new Object[] {null, null}); } } for (int i = 0; st1.hasMoreTokens(); i++) { rowstring = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(rowstring, "\t"); for (int j = 0; st2.hasMoreTokens(); j++) { value = st2.nextToken(); if (j < jTable1.getColumnCount()) { jTable1.setValueAt(value, i, j); } if (debug) { System.out.println( "Putting " + value + "at row=" + (startRow + i) + "column=" + (startCol + j)); } } } } catch (Exception ex) { ex.printStackTrace(); ((DefaultTableModel) jTable1.getModel()).addRow(new Object[] {null, null}); } jTable1 .getParent() .getParent() .getParent() .setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } }