private void setSelection(int rowAnchor, int rowLead, int colAnchor, int colLead) { setAnchor(rowAnchor, colAnchor); setLead(rowLead, colLead); table.setRowSelectionInterval( clamp(rowAnchor, 0, numUsableRows), clamp(rowLead, 0, numUsableRows)); table.setColumnSelectionInterval(colAnchor, colLead); }
/** * Create a Transferable to use as the source for a data transfer. * * @param c The component holding the data to be transfered. This argument is provided to enable * sharing of TransferHandlers by multiple components. * @return The representation of the data to be transfered. */ protected Transferable createTransferable(JComponent c) { Object[] values = null; if (c instanceof JList) { values = ((JList) c).getSelectedValues(); } else if (c instanceof JTable) { JTable table = (JTable) c; int[] rows = table.getSelectedRows(); if (rows != null) { values = new Object[rows.length]; for (int i = 0; i < rows.length; i++) { values[i] = table.getValueAt(rows[i], 0); } } } if (values == null || values.length == 0) { return null; } StringBuffer plainBuf = new StringBuffer(); StringBuffer htmlBuf = new StringBuffer(); htmlBuf.append("<html>\n<body>\n<ul>\n"); for (Object obj : values) { String val = ((obj == null) ? "" : obj.toString()); plainBuf.append(val + "\n"); htmlBuf.append(" <li>" + val + "\n"); } // remove the last newline plainBuf.deleteCharAt(plainBuf.length() - 1); htmlBuf.append("</ul>\n</body>\n</html>"); return new FileTransferable(plainBuf.toString(), htmlBuf.toString(), values); }
/** * Set the current open DarwinCSV. You should really, really, really setCurrentCSV(null) before * you load a new DarwinCSV. * * @param csv The new DarwinCSV object. */ private void setCurrentCSV(DarwinCSV csv) { // Clear the old currentCSV object and matchAgainst object. currentCSV = null; matchAgainst(null); // Load the new currentCSV object. currentCSV = csv; table.removeAll(); table.setDefaultRenderer(Name.class, this); // Set the currentCSV // TODO: This causes an exception occasionally, because we shouldn't // be calling setModel outside of the Event Queue thread; however, we're // currently in a worker thread, so dipping back into the Event thread // would just cause more problems. Sorry! if (csv != null) { table.setModel(currentCSV.getRowIndex()); } else { table.setModel(blankDataModel); } columnInfoPanel.loadedFileChanged(csv); columnInfoPanel.columnChanged(-1); table.repaint(); }
/** * 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. */ public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuffer sbf = new StringBuffer(); // Check to ensure we have selected only a contiguous block of // cells int numcols = jTable1.getSelectedColumnCount(); int numrows = jTable1.getSelectedRowCount(); int[] rowsselected = jTable1.getSelectedRows(); int[] colsselected = jTable1.getSelectedColumns(); if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) { JOptionPane.showMessageDialog( null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { sbf.append(jTable1.getValueAt(rowsselected[i], colsselected[j])); if (j < 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) { System.out.println("Trying to Paste"); int startRow = (jTable1.getSelectedRows())[0]; int startCol = (jTable1.getSelectedColumns())[0]; try { String trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor)); System.out.println("String is:" + trstring); StringTokenizer st1 = new StringTokenizer(trstring, "\n"); for (int i = 0; st1.hasMoreTokens(); i++) { rowstring = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(rowstring, "\t"); for (int j = 0; st2.hasMoreTokens(); j++) { value = (String) st2.nextToken(); if (startRow + i < jTable1.getRowCount() && startCol + j < jTable1.getColumnCount()) jTable1.setValueAt(value, startRow + i, startCol + j); System.out.println( "Putting " + value + "at row = " + startRow + i + "column = " + startCol + j); } } } catch (Exception ex) { ex.printStackTrace(); } } }
/** * The Excel Adapter is constructed with a JTable on which it enables Copy-Paste and acts as a * Clipboard listener. */ public ExcelAdapter(JTable myJTable) { jTable1 = myJTable; KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK, false); // Identifying the copy KeyStroke user can modify this // to copy on some other Key combination. KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK, false); // Identifying the Paste KeyStroke user can modify this // to copy on some other Key combination. jTable1.registerKeyboardAction(this, "Copy", copy, JComponent.WHEN_FOCUSED); jTable1.registerKeyboardAction(this, "Paste", paste, JComponent.WHEN_FOCUSED); system = Toolkit.getDefaultToolkit().getSystemClipboard(); }
/** * Set the DarwinCSV to match this against. * * @param against The DarwinCSV object to match against. */ private void matchAgainst(DarwinCSV against) { // System.err.println("matchAgainst: " + against); // Reset previous match information. currentMatch = null; table.repaint(); // If all we're doing is a reset, we can get out now. if (against == null) return; // long t1 = System.currentTimeMillis(); currentMatch = currentCSV.getRowIndex().matchAgainst(against.getRowIndex()); table.repaint(); matchInfoPanel.matchChanged(currentMatch); // long t2 = System.currentTimeMillis(); // System.err.println("matchAgainst finished: " + (t2 - t1) + " ms"); }
public void jTable1_keyPressed(KeyEvent e) { if (e.getKeyCode() == 127) { int[] selected = jTable1.getSelectedRows(); for (int i = selected.length - 1; i >= 0; i--) { model.removeRow(selected[i]); model.fireTableDataChanged(); } } }
private void maybeGrabSelection() { if (table.getSelectedRow() != -1) { // Grab selection ListSelectionModel rowSel = table.getSelectionModel(); ListSelectionModel colSel = table.getColumnModel().getSelectionModel(); if (!haveAnchor()) { // System.err.println("Updating from table's selection"); setSelection( rowSel.getAnchorSelectionIndex(), rowSel.getLeadSelectionIndex(), colSel.getAnchorSelectionIndex(), colSel.getLeadSelectionIndex()); } else { // System.err.println("Updating lead from table's selection"); setSelection( getRowAnchor(), rowSel.getLeadSelectionIndex(), getColAnchor(), colSel.getLeadSelectionIndex()); } // printSelection(); } }
private void recomputeNumVisibleRows() { Rectangle rect = new Rectangle(); getBounds(rect); int h = table.getRowHeight(); numVisibleRows = (rect.height + (h - 1)) / h; numUsableRows = numVisibleRows - 2; scrollBar.setBlockIncrementHP(new BigInteger(Integer.toString(addressSize * (numUsableRows)))); model.fireTableDataChanged(); // FIXME: refresh selection }
protected void toWindow() { table = new JTable(model); if (!viewHeaders) { table.setTableHeader(null); } table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); // table.setCellSelectionEnabled(true); table.setEnabled(false); scrollPane = new JScrollPane(table); /* * scrollPane.setPreferredSize(getSize()); * scrollPane.setSize(getSize()); */ add(scrollPane, BorderLayout.CENTER); }
void goToSpecificColumn(int selectedIndex) { int row = table.getSelectedRow(); table.changeSelection(row, selectedIndex, true, true); }
/** * Move the currently selected cell up or down by one cell. * * @param direction -1 for previous, +1 for next. */ public void goToRow(int direction) { int row = table.getSelectedRow(); int column = table.getSelectedColumn(); table.changeSelection(row + direction, column, false, false); }
/** * Create a new, empty, not-visible TaxRef window. Really just activates the setup frame and setup * memory monitor components, then starts things off. */ public MainFrame() { setupMemoryMonitor(); // Set up the main frame. mainFrame = new JFrame(basicTitle); mainFrame.setJMenuBar(setupMenuBar()); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set up the JTable. table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setSelectionBackground(COLOR_SELECTION_BACKGROUND); table.setShowGrid(true); // Add a blank table model so that the component renders properly on // startup. table.setModel(blankDataModel); // Add a list selection listener so we can tell the matchInfoPanel // that a new name was selected. table .getSelectionModel() .addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (currentCSV == null) return; int row = table.getSelectedRow(); int column = table.getSelectedColumn(); columnInfoPanel.columnChanged(column); Object o = table.getModel().getValueAt(row, column); if (Name.class.isAssignableFrom(o.getClass())) { matchInfoPanel.nameSelected(currentCSV.getRowIndex(), (Name) o, row, column); } else { matchInfoPanel.nameSelected(currentCSV.getRowIndex(), null, -1, -1); } } }); // Set up the left panel (table + matchInfoPanel) JPanel leftPanel = new JPanel(); matchInfoPanel = new MatchInformationPanel(this); leftPanel.setLayout(new BorderLayout()); leftPanel.add(matchInfoPanel, BorderLayout.SOUTH); leftPanel.add(new JScrollPane(table)); // Set up the right panel (columnInfoPanel) JPanel rightPanel = new JPanel(); columnInfoPanel = new ColumnInformationPanel(this); progressBar.setStringPainted(true); rightPanel.setLayout(new BorderLayout()); rightPanel.add(columnInfoPanel); rightPanel.add(progressBar, BorderLayout.SOUTH); // Set up a JSplitPane to split the panels up. JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, leftPanel, rightPanel); split.setResizeWeight(1); mainFrame.add(split); mainFrame.pack(); // Set up a drop target so we can pick up files mainFrame.setDropTarget( new DropTarget( mainFrame, new DropTargetAdapter() { @Override public void dragEnter(DropTargetDragEvent dtde) { // Accept any drags. dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); } @Override public void dragOver(DropTargetDragEvent dtde) {} @Override public void dropActionChanged(DropTargetDragEvent dtde) {} @Override public void dragExit(DropTargetEvent dte) {} @Override public void drop(DropTargetDropEvent dtde) { // Accept a drop as long as its File List. if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); Transferable t = dtde.getTransferable(); try { java.util.List<File> files = (java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor); // If we're given multiple files, pick up only the last file and load that. File f = files.get(files.size() - 1); loadFile(f, DarwinCSV.FILE_CSV_DELIMITED); } catch (UnsupportedFlavorException ex) { dtde.dropComplete(false); } catch (IOException ex) { dtde.dropComplete(false); } } } })); }
public MemoryPanel(final Debugger debugger, boolean is64Bit) { super(); this.debugger = debugger; this.is64Bit = is64Bit; if (is64Bit) { addressSize = 8; unmappedAddrString = "??????????????????"; } else { addressSize = 4; unmappedAddrString = "??????????"; } setLayout(new BorderLayout()); setupScrollBar(); add(scrollBar, BorderLayout.EAST); model = new AbstractTableModel() { public int getRowCount() { return numVisibleRows; } public int getColumnCount() { return 2; } public Object getValueAt(int row, int column) { switch (column) { case 0: return bigIntToHexString( startVal.add(new BigInteger(Integer.toString((row * addressSize))))); case 1: { try { Address addr = bigIntToAddress( startVal.add(new BigInteger(Integer.toString((row * addressSize))))); if (addr != null) { return addressToString(addr.getAddressAt(0)); } return unmappedAddrString; } catch (UnmappedAddressException e) { return unmappedAddrString; } } default: throw new RuntimeException("Column " + column + " out of bounds"); } } public boolean isCellEditable(int row, int col) { return false; } }; // View with JTable with no header table = new JTable(model); table.setTableHeader(null); table.setShowGrid(false); table.setIntercellSpacing(new Dimension(0, 0)); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); table.setDragEnabled(true); Font font = GraphicsUtilities.lookupFont("Courier"); if (font == null) { throw new RuntimeException("Error looking up monospace font Courier"); } table.setFont(font); // Export proper data. // We need to keep our own notion of the selection in order to // properly export data, since the selection can go beyond the // visible area on the screen (and since the table's model doesn't // back all of those slots). // Code thanks to Shannon.Hickey@sfbay table.setTransferHandler( new TransferHandler() { protected Transferable createTransferable(JComponent c) { JTable table = (JTable) c; if (haveSelection()) { StringBuffer buf = new StringBuffer(); int iDir = (getRowAnchor() < getRowLead() ? 1 : -1); int jDir = (getColAnchor() < getColLead() ? 1 : -1); for (int i = getRowAnchor(); i != getRowLead() + iDir; i += iDir) { for (int j = getColAnchor(); j != getColLead() + jDir; j += jDir) { Object val = model.getValueAt(i, j); buf.append(val == null ? "" : val.toString()); if (j != getColLead()) { buf.append("\t"); } } if (i != getRowLead()) { buf.append("\n"); } } return new StringTransferable(buf.toString()); } return null; } public int getSourceActions(JComponent c) { return COPY; } public boolean importData(JComponent c, Transferable t) { if (canImport(c, t.getTransferDataFlavors())) { try { String str = (String) t.getTransferData(DataFlavor.stringFlavor); handleImport(c, str); return true; } catch (UnsupportedFlavorException ufe) { } catch (IOException ioe) { } } return false; } public boolean canImport(JComponent c, DataFlavor[] flavors) { for (int i = 0; i < flavors.length; i++) { if (DataFlavor.stringFlavor.equals(flavors[i])) { return true; } } return false; } private void handleImport(JComponent c, String str) { // do whatever you want with the string here try { makeVisible(debugger.parseAddress(str)); clearSelection(); table.clearSelection(); } catch (NumberFormatException e) { System.err.println("Unable to parse address \"" + str + "\""); } } }); // Supporting keyboard scrolling // See src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java, // search for Table.AncestorInputMap // Actions to override: // selectPreviousRow, selectNextRow, // scrollUpChangeSelection, scrollDownChangeSelection, // selectPreviousRowExtendSelection, selectNextRowExtendSelection, // scrollDownExtendSelection, scrollUpExtendSelection (Shift-PgDn/PgUp) ActionMap map = table.getActionMap(); // Up arrow installActionWrapper( map, "selectPreviousRow", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); clearSelection(); if (table.getSelectedRow() == 0) { scrollBar.scrollUpOrLeft(); table.setRowSelectionInterval(0, 0); } else { super.actionPerformed(e); } maybeGrabSelection(); endUpdate(); } }); // Down arrow installActionWrapper( map, "selectNextRow", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); clearSelection(); int row = table.getSelectedRow(); if (row >= numUsableRows) { scrollBar.scrollDownOrRight(); table.setRowSelectionInterval(row, row); } else { super.actionPerformed(e); } maybeGrabSelection(); endUpdate(); } }); // Page up installActionWrapper( map, "scrollUpChangeSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); clearSelection(); int row = table.getSelectedRow(); scrollBar.pageUpOrLeft(); if (row >= 0) { table.setRowSelectionInterval(row, row); } maybeGrabSelection(); endUpdate(); } }); // Page down installActionWrapper( map, "scrollDownChangeSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); clearSelection(); int row = table.getSelectedRow(); scrollBar.pageDownOrRight(); if (row >= 0) { table.setRowSelectionInterval(row, row); } maybeGrabSelection(); endUpdate(); } }); // Shift + Up arrow installActionWrapper( map, "selectPreviousRowExtendSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); if (!haveAnchor()) { setAnchorFromTable(); setLeadFromTable(); // setAnchor(table.getSelectedRow()); // setLead(table.getSelectedRow()); } int newLead = getRowLead() - 1; int newAnchor = getRowAnchor(); if (newLead < 0) { scrollBar.scrollUpOrLeft(); ++newLead; ++newAnchor; } setSelection(newAnchor, newLead, getColAnchor(), getColLead()); // printSelection(); endUpdate(); } }); // Shift + Left arrow installActionWrapper( map, "selectPreviousColumnExtendSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); if (!haveAnchor()) { setAnchorFromTable(); setLeadFromTable(); } int newLead = Math.max(0, getColLead() - 1); setSelection(getRowAnchor(), getRowLead(), getColAnchor(), newLead); // printSelection(); endUpdate(); } }); // Shift + Down arrow installActionWrapper( map, "selectNextRowExtendSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); if (!haveAnchor()) { setAnchorFromTable(); setLeadFromTable(); // setAnchor(table.getSelectedRow()); // setLead(table.getSelectedRow()); } int newLead = getRowLead() + 1; int newAnchor = getRowAnchor(); if (newLead > numUsableRows) { scrollBar.scrollDownOrRight(); --newLead; --newAnchor; } setSelection(newAnchor, newLead, getColAnchor(), getColLead()); // printSelection(); endUpdate(); } }); // Shift + Right arrow installActionWrapper( map, "selectNextColumnExtendSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); if (!haveAnchor()) { setAnchorFromTable(); setLeadFromTable(); } int newLead = Math.min(model.getColumnCount() - 1, getColLead() + 1); setSelection(getRowAnchor(), getRowLead(), getColAnchor(), newLead); // printSelection(); endUpdate(); } }); // Shift + Page up installActionWrapper( map, "scrollUpExtendSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); if (!haveAnchor()) { setAnchorFromTable(); setLeadFromTable(); // setAnchor(table.getSelectedRow()); // setLead(table.getSelectedRow()); } int newLead = getRowLead() - numUsableRows; int newAnchor = getRowAnchor(); if (newLead < 0) { scrollBar.pageUpOrLeft(); newLead += numUsableRows; newAnchor += numUsableRows; } setSelection(newAnchor, newLead, getColAnchor(), getColLead()); // printSelection(); endUpdate(); } }); // Shift + Page down installActionWrapper( map, "scrollDownExtendSelection", new ActionWrapper() { public void actionPerformed(ActionEvent e) { beginUpdate(); if (!haveAnchor()) { setAnchorFromTable(); setLeadFromTable(); // setAnchor(table.getSelectedRow()); // setLead(table.getSelectedRow()); } int newLead = getRowLead() + numUsableRows; int newAnchor = getRowAnchor(); if (newLead > numUsableRows) { scrollBar.pageDownOrRight(); newLead -= numUsableRows; newAnchor -= numUsableRows; } setSelection(newAnchor, newLead, getColAnchor(), getColLead()); // printSelection(); endUpdate(); } }); // Clear our notion of selection upon mouse press table.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { if (shouldIgnore(e)) { return; } // Make shift-clicking work properly if (e.isShiftDown()) { maybeGrabSelection(); return; } // System.err.println(" Clearing selection on mouse press"); clearSelection(); } }); // Watch for mouse going out of bounds table.addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (shouldIgnore(e)) { // System.err.println(" (Ignoring consumed mouse event)"); return; } // Look for drag events outside table and scroll if necessary Point p = e.getPoint(); if (table.rowAtPoint(p) == -1) { // See whether we are above or below the table Rectangle rect = new Rectangle(); getBounds(rect); beginUpdate(); if (p.y < rect.y) { // System.err.println(" Scrolling up due to mouse event"); // Scroll up scrollBar.scrollUpOrLeft(); setSelection(getRowAnchor(), 0, getColAnchor(), getColLead()); } else { // System.err.println(" Scrolling down due to mouse event"); // Scroll down scrollBar.scrollDownOrRight(); setSelection(getRowAnchor(), numUsableRows, getColAnchor(), getColLead()); } // printSelection(); endUpdate(); } else { maybeGrabSelection(); } } }); add(table, BorderLayout.CENTER); // Make sure we recompute number of visible rows addComponentListener( new ComponentAdapter() { public void componentResized(ComponentEvent e) { recomputeNumVisibleRows(); constrain(); } }); addHierarchyListener( new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { recomputeNumVisibleRows(); constrain(); } }); updateFromScrollBar(); }
private void setLeadFromTable() { setLead( table.getSelectionModel().getAnchorSelectionIndex(), table.getColumnModel().getSelectionModel().getAnchorSelectionIndex()); }
private boolean shouldIgnore(MouseEvent e) { return e.isConsumed() || (!(SwingUtilities.isLeftMouseButton(e) && table.isEnabled())); }