001package jmri.util;
002
003import java.awt.datatransfer.DataFlavor;
004import java.awt.datatransfer.Transferable;
005import java.awt.datatransfer.UnsupportedFlavorException;
006import java.io.IOException;
007import javax.swing.JComponent;
008import javax.swing.JTextField;
009import javax.swing.TransferHandler;
010import org.slf4j.Logger;
011import org.slf4j.LoggerFactory;
012
013/**
014 * Simple TransferHandler that overwrites the text in a JTextField component.
015 * Use JTextField default handler if you want insertion.
016 *
017 * @author Pete Cressman Copyright 2010
018 */
019public class DnDStringImportHandler extends TransferHandler {
020
021    /////////////////////import
022    @Override
023    public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
024        //if (log.isDebugEnabled()) log.debug("DnDStringImportHandler.canImport ");
025        for (int k = 0; k < transferFlavors.length; k++) {
026            if (transferFlavors[k].equals(DataFlavor.stringFlavor)) {
027                return true;
028            }
029        }
030        return false;
031    }
032
033    @Override
034    public boolean importData(JComponent comp, Transferable tr) {
035        //if (log.isDebugEnabled()) log.debug("DnDStringImportHandler.importData ");
036        DataFlavor[] flavors =  tr.getTransferDataFlavors();
037
038        if ((!canImport(comp, flavors)) || (!(comp instanceof JTextField)) ) {
039            return false;
040        }
041        try {
042            String data = (String) tr.getTransferData(DataFlavor.stringFlavor);
043            JTextField field = (JTextField) comp;
044            field.setText(data);
045            //Notify listeners drop happened
046            field.firePropertyChange("DnDrop", 0, 1);
047            return true;
048        } catch (UnsupportedFlavorException | IOException ufe) {
049            log.warn("DnDStringImportHandler.importData: {}", ufe.getMessage());
050        }
051        return false;
052    }
053    private final static Logger log = LoggerFactory.getLogger(DnDStringImportHandler.class);
054}