001package jmri.util;
002
003/**
004 * Simple TransferHandler that exports a string value of a cell in a JTable.
005 *
006 * @author Pete Cressman Copyright 2010
007 */
008import java.awt.datatransfer.StringSelection;
009import java.awt.datatransfer.Transferable;
010import javax.swing.JComponent;
011import javax.swing.JTable;
012import javax.swing.TransferHandler;
013import org.slf4j.Logger;
014import org.slf4j.LoggerFactory;
015
016public class DnDTableExportHandler extends TransferHandler {
017
018    @Override
019    public int getSourceActions(JComponent c) {
020        return COPY;
021    }
022
023    @Override
024    public Transferable createTransferable(JComponent c) {
025        if (!(c instanceof JTable)) {
026            return null;
027        }
028        JTable table = (JTable) c;
029        int col = table.getSelectedColumn();
030        int row = table.getSelectedRow();
031        if (col < 0 || row < 0) {
032            return null;
033        }
034        row = table.convertRowIndexToModel(row);
035        col = table.convertColumnIndexToModel(col);
036        if (log.isDebugEnabled()) {
037            log.debug("TransferHandler.createTransferable: from ({}, {}) for \"{}\"", row, col, table.getModel().getValueAt(row, col));
038        }
039        Object obj = table.getModel().getValueAt(row, col);
040        if (obj instanceof String) {
041            return new StringSelection((String) obj);
042        } else if (obj != null) {
043            return new StringSelection(obj.getClass().getName());
044        } else {
045            return null;
046        }
047    }
048
049    @Override
050    public void exportDone(JComponent c, Transferable t, int action) {
051        if (log.isDebugEnabled()) {
052            log.debug("TransferHandler.exportDone ");
053        }
054    }
055    private final static Logger log = LoggerFactory.getLogger(DnDTableExportHandler.class);
056}