/** * 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); }
/** Handle string insertion. */ public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { // Store source data int sourceLength = getLength(); String sourceText = getText(0, sourceLength); StringBuffer strBuffer = new StringBuffer(sourceText); // Check if old value is zero if (offs == 0 && sourceLength > 0 && str.length() > 0) { long oldValue; try { oldValue = myFormat.parse(strBuffer.toString()).longValue(); if (oldValue == 0) { strBuffer.deleteCharAt(0); } } catch (Exception e) { } } // Now add new string strBuffer.insert(offs, str); BigDecimal value; try { value = new BigDecimal(myFormat.parse(strBuffer.toString()).doubleValue()); } catch (Exception e) { if (sourceLength > 0) { if (sourceText.startsWith(",")) { sourceText = "0" + sourceText; } value = new BigDecimal(getRealString(sourceText)); } else { value = new BigDecimal(0.0); } } // Set the new value if (textField == null) { return; } textField.setValue(new Money(value, textField.getValue().getCurrency()), false); super.remove(0, sourceLength); super.insertString(0, myFormat.format(value.doubleValue()), a); // Set caret to correct caret position if (!"".equals(sourceText)) // <=> initilized { int lengthDiff = getLength() - sourceLength; int caretPos = lengthDiff + offs; int caretDiff = sourceLength - offs; // Adjust for columns after centSperator (currently Diff < 3) if ((caretDiff > 0 && caretDiff < 3) || (value.abs().longValue() < 10 && caretPos == 0)) { caretPos += 1; } if (caretPos < 0) { caretPos = 0; } textField.setCaretPosition(caretPos); } else { textField.setCaretPosition(1); } }