001package jmri.util;
002
003import java.awt.Component;
004import java.awt.datatransfer.DataFlavor;
005import java.awt.datatransfer.Transferable;
006import java.awt.datatransfer.UnsupportedFlavorException;
007import java.io.IOException;
008import javax.swing.JTable;
009import javax.swing.TransferHandler;
010import org.slf4j.Logger;
011import org.slf4j.LoggerFactory;
012
013/**
014 * Simple TransferHandler that imports and exports Strings into JTable cells.
015 *
016 * @author Pete Cressman Copyright 2016
017 */
018public class DnDTableImportExportHandler extends DnDTableExportHandler {
019    
020    int[] _skipColumns = new int[]{};
021
022    public DnDTableImportExportHandler() {
023        super();
024    }
025    /**
026     * Constructor for import/export of JTable cells
027     * @param skipCols array of column indices to refuse importing
028     */
029    public DnDTableImportExportHandler(int[] skipCols) {
030        super();
031        if (skipCols!=null) {
032            _skipColumns = skipCols;
033        }
034    }
035
036    @Override
037    public boolean canImport(TransferHandler.TransferSupport support) {
038        DataFlavor[] flavors =  support.getDataFlavors();
039        for (int k = 0; k < flavors.length; k++) {
040            if (flavors[k].equals(DataFlavor.stringFlavor)) {
041                return true;
042            }
043        }
044        return false;
045    }
046
047    @Override
048    public boolean importData(TransferHandler.TransferSupport support) {
049        if (!canImport(support)) {
050            return false;
051        }
052        TransferHandler.DropLocation loc = support.getDropLocation();
053        Component comp = support.getComponent();
054        if (!support.isDrop() || (!(loc instanceof JTable.DropLocation)) || (!(comp instanceof JTable))   ) {
055            return false;            
056        }
057        JTable.DropLocation location = (JTable.DropLocation)loc;
058        log.debug("importData: location= {} row= {} col= {}", loc.getDropPoint(), location.getRow(),location.getColumn());
059        JTable table = (JTable)comp;
060        int row = table.convertRowIndexToModel(location.getRow());
061        int col = table.convertColumnIndexToModel(location.getColumn());
062        for (int i = 0; i < _skipColumns.length; i++) {
063            if (_skipColumns[i] == col) {
064                return false;
065            }
066        }
067        try {
068            Transferable trans = support.getTransferable();
069            Object obj = trans.getTransferData(DataFlavor.stringFlavor);
070            table.getModel().setValueAt(obj, row, col);
071            return true;
072        } catch (UnsupportedFlavorException | IOException ufe) {
073            log.warn("DnDStringImportHandler.importData: {}", ufe.getMessage());
074        }
075        return false;
076    }
077    private final static Logger log = LoggerFactory.getLogger(DnDTableImportExportHandler.class);
078}