PageRenderTime 84ms CodeModel.GetById 68ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/src/mpv5/utils/tables/ExcelAdapter.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 146 lines | 80 code | 32 blank | 34 comment | 20 complexity | 3c129b28f4baa598e995ac28a2e265dc MD5 | raw file
  1package mpv5.utils.tables;
  2
  3//~--- JDK imports ------------------------------------------------------------
  4
  5import java.awt.*;
  6import java.awt.datatransfer.*;
  7import java.awt.event.*;
  8
  9import java.util.*;
 10
 11import javax.swing.*;
 12
 13/**
 14 * @author http://www.javaworld.com/javaworld/javatips/jw-javatip77.html
 15 * ExcelAdapter enables Copy-Paste Clipboard functionality on JTables.
 16 * The clipboard data format used by the adapter is compatible with
 17 * the clipboard format used by Excel. This provides for clipboard
 18 * interoperability between enabled JTables and Excel.
 19 */
 20public class ExcelAdapter implements ActionListener {
 21    private JTable          jTable1;
 22    private String          rowstring, value;
 23    private StringSelection stsel;
 24    private Clipboard       system;
 25
 26    /**
 27     * The Excel Adapter is constructed with a
 28     * JTable on which it enables Copy-Paste and acts
 29     * as a Clipboard listener.
 30     */
 31    public ExcelAdapter(JTable myJTable) {
 32        jTable1 = myJTable;
 33
 34        KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK, false);
 35
 36        // Identifying the copy KeyStroke user can modify this
 37        // to copy on some other Key combination.
 38        KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK, false);
 39
 40        // Identifying the Paste KeyStroke user can modify this
 41        // to copy on some other Key combination.
 42        jTable1.registerKeyboardAction(this, "Copy", copy, JComponent.WHEN_FOCUSED);
 43        jTable1.registerKeyboardAction(this, "Paste", paste, JComponent.WHEN_FOCUSED);
 44        system = Toolkit.getDefaultToolkit().getSystemClipboard();
 45    }
 46
 47    /**
 48     * Public Accessor methods for the Table on which this adapter acts.
 49     */
 50    public JTable getJTable() {
 51        return jTable1;
 52    }
 53
 54    public void setJTable(JTable jTable1) {
 55        this.jTable1 = jTable1;
 56    }
 57
 58    /**
 59     * This method is activated on the Keystrokes we are listening to
 60     * in this implementation. Here it listens for Copy and Paste ActionCommands.
 61     * Selections comprising non-adjacent cells result in invalid selection and
 62     * then copy action cannot be performed.
 63     * Paste is done by aligning the upper left corner of the selection with the
 64     * 1st element in the current selection of the JTable.
 65     */
 66    public void actionPerformed(ActionEvent e) {
 67        if (e.getActionCommand().compareTo("Copy") == 0) {
 68            StringBuffer sbf = new StringBuffer();
 69
 70            // Check to ensure we have selected only a contiguous block of
 71            // cells
 72            int   numcols      = jTable1.getSelectedColumnCount();
 73            int   numrows      = jTable1.getSelectedRowCount();
 74            int[] rowsselected = jTable1.getSelectedRows();
 75            int[] colsselected = jTable1.getSelectedColumns();
 76
 77            if (!(((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0])
 78                    && (numrows == rowsselected.length)) && ((numcols - 1
 79                        == colsselected[colsselected.length - 1] - colsselected[0]) && (numcols
 80                            == colsselected.length)))) {
 81                JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection",
 82                                              JOptionPane.ERROR_MESSAGE);
 83
 84                return;
 85            }
 86
 87            for (int i = 0; i < numrows; i++) {
 88                for (int j = 0; j < numcols; j++) {
 89                    String s = String.valueOf(jTable1.getValueAt(rowsselected[i],
 90                                   colsselected[j])).replaceAll("\\<.*?\\>", "");
 91
 92                    if (s.equals("null")) {
 93                        s = "";
 94                    }
 95
 96                    sbf.append(s);
 97
 98                    if (j < numcols - 1) {
 99                        sbf.append("\t");
100                    }
101                }
102
103                sbf.append("\n");
104            }
105
106            stsel  = new StringSelection(sbf.toString());
107            system = Toolkit.getDefaultToolkit().getSystemClipboard();
108            system.setContents(stsel, stsel);
109        }
110
111        if (e.getActionCommand().compareTo("Paste") == 0) {
112
113            // System.out.println("Trying to Paste");
114            int startRow = (jTable1.getSelectedRows())[0];
115            int startCol = (jTable1.getSelectedColumns())[0];
116
117            try {
118                String trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor));
119
120                // System.out.println("String is:" + trstring);
121                StringTokenizer st1 = new StringTokenizer(trstring, "\n");
122
123                for (int i = 0; st1.hasMoreTokens(); i++) {
124                    rowstring = st1.nextToken();
125
126                    StringTokenizer st2 = new StringTokenizer(rowstring, "\t");
127
128                    for (int j = 0; st2.hasMoreTokens(); j++) {
129                        value = (String) st2.nextToken();
130
131                        if ((startRow + i < jTable1.getRowCount()) && (startCol + j < jTable1.getColumnCount())) {
132                            jTable1.setValueAt(value, startRow + i, startCol + j);
133                        }
134
135                        // System.out.println("Putting " + value + "atrow=" + startRow + i + "column=" + startCol + j);
136                    }
137                }
138            } catch (Exception ex) {
139                ex.printStackTrace();
140            }
141        }
142    }
143}
144
145
146//~ Formatted by Jindent --- http://www.jindent.com