Example usage for java.awt.datatransfer DataFlavor javaFileListFlavor

List of usage examples for java.awt.datatransfer DataFlavor javaFileListFlavor

Introduction

In this page you can find the example usage for java.awt.datatransfer DataFlavor javaFileListFlavor.

Prototype

DataFlavor javaFileListFlavor

To view the source code for java.awt.datatransfer DataFlavor javaFileListFlavor.

Click Source Link

Document

To transfer a list of files to/from Java (and the underlying platform) a DataFlavor of this type/subtype and representation class of java.util.List is used.

Usage

From source file:io.neocdtv.simpleplayer.ui.PlaylistTransferHandler.java

@Override
public boolean importData(TransferHandler.TransferSupport info) {
    if (!info.isDrop()) {
        return false;
    }/*from  ww w.  ja  v a  2  s  .c  om*/

    JList list = (JList) info.getComponent();
    DefaultListModel<PlaylistEntry> listModel = (DefaultListModel) list.getModel();
    JList.DropLocation dropLocation = (JList.DropLocation) info.getDropLocation();

    // Get the string that is being dropped.
    Transferable transferable = info.getTransferable();
    List<File> data;
    try {
        data = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
        for (File file : data) {
            if (file.isDirectory()) {
                final boolean recursive = true;
                final String[] fileExtensionFilter = null;
                final List<File> listFiles = Arrays.asList(FileUtils.convertFileCollectionToFileArray(
                        FileUtils.listFiles(file, fileExtensionFilter, recursive)));
                for (File o : listFiles) {
                    listModel.addElement(buildEntry(o));
                }
            } else {
                listModel.addElement(buildEntry(file));
            }
        }
    } catch (UnsupportedFlavorException | IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:ColorSink.java

public void dragEnter(DropTargetDragEvent e) {
    if (e.isDataFlavorSupported(TransferableColor.colorFlavor)
            || e.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
        e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
        this.setBorder(dropBorder);
    }//from   w  w  w. ja va  2s. c om
}

From source file:HostPanel.java

/**
 * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
 *///from   w w w .  java 2s .  c o  m
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    dropTargetScroll = new javax.swing.JScrollPane();
    dropTargetArea = new javax.swing.JTextArea();
    dropTargetTitle = new javax.swing.JLabel();
    globalProgress = new javax.swing.JProgressBar();
    currentProgress = new javax.swing.JProgressBar();
    transferButton = new javax.swing.JButton();
    dropTargetValue = new javax.swing.JLabel();
    dropTargetClear = new javax.swing.JLabel();
    statusDisplay1 = new javax.swing.JLabel();
    statusDisplay2 = new javax.swing.JLabel();

    setFocusable(false);

    dropTargetScroll.setFocusable(false);

    dropTargetArea.setDropTarget(new DropTarget() {
        @Override
        public synchronized void drop(DropTargetDropEvent evt) {
            if (transfer == null || transfer.isDone()) {
                evt.acceptDrop(DnDConstants.ACTION_LINK);
                Transferable transferable = evt.getTransferable();

                try {
                    if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        ProcessDropTarget pdt = new ProcessDropTarget(
                                (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor));
                        pdt.execute();
                    }
                } catch (UnsupportedFlavorException | IOException ex) {
                    Logger.getLogger(HostPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });
    dropTargetArea.setEditable(false);
    dropTargetArea.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
    dropTargetArea.setFocusable(false);
    dropTargetScroll.setViewportView(dropTargetArea);

    dropTargetTitle.setText("Drag files to host onto box below");
    dropTargetTitle.setFocusable(false);

    globalProgress.setFocusable(false);
    globalProgress.setRequestFocusEnabled(false);
    globalProgress.setStringPainted(true);

    currentProgress.setFocusable(false);
    currentProgress.setRequestFocusEnabled(false);
    currentProgress.setStringPainted(true);

    transferButton.setText("Host");
    transferButton.setActionCommand("host");
    transferButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            transferButtonActionPerformed(evt);
        }
    });

    dropTargetValue.setText("Files to Share: 0");
    dropTargetValue.setFocusable(false);

    dropTargetClear.setText("Clear");
    dropTargetClear.setFocusable(false);
    dropTargetClear.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseReleased(java.awt.event.MouseEvent evt) {
            dropTargetClearMouseReleased(evt);
        }
    });

    statusDisplay1.setText("");

    statusDisplay2.setText("");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dropTargetScroll)
                            .addGroup(layout.createSequentialGroup().addGroup(
                                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(globalProgress, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                    165, Short.MAX_VALUE)
                                            .addComponent(currentProgress, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGap(18, 18, 18)
                                    .addGroup(layout
                                            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(statusDisplay1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                    359, Short.MAX_VALUE)
                                            .addComponent(statusDisplay2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGap(18, 18, 18)
                                    .addComponent(transferButton, javax.swing.GroupLayout.PREFERRED_SIZE, 120,
                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup().addComponent(dropTargetTitle)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(dropTargetValue, javax.swing.GroupLayout.PREFERRED_SIZE, 136,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18).addComponent(dropTargetClear)))
                    .addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            javax.swing.GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup().addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(dropTargetTitle).addComponent(dropTargetValue)
                            .addComponent(dropTargetClear))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(dropTargetScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup().addGroup(layout
                                    .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(currentProgress, javax.swing.GroupLayout.PREFERRED_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(statusDisplay1))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout
                                            .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(globalProgress,
                                                    javax.swing.GroupLayout.PREFERRED_SIZE,
                                                    javax.swing.GroupLayout.DEFAULT_SIZE,
                                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(statusDisplay2)))
                            .addComponent(transferButton, javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap()));
}

From source file:FileTransferHandler.java

/**
 * If the wrapped handler can import strings and the specified Transferable
 * can provide its data as a List of File objects, then we read the files, and
 * pass their contents as a string to the wrapped handler. Otherwise, we offer
 * the Transferable to the wrapped handler to handle on its own.
 *///from   www.  j a  v  a 2  s  .co  m
public boolean importData(JComponent c, Transferable t) {
    // See if we're offered a java.util.List of java.io.File objects.
    // We handle this case first because the Transferable is likely to
    // also offer the filenames as strings, and we want to import the
    // file contents, not their names!
    if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)
            && wrappedHandler.canImport(c, stringFlavorArray)) {
        try {
            List filelist = (List) t.getTransferData(DataFlavor.javaFileListFlavor);

            // Loop through the files to determine total size
            int numfiles = filelist.size();
            int numbytes = 0;
            for (int i = 0; i < numfiles; i++) {
                File f = (File) filelist.get(i);
                numbytes += (int) f.length();
            }

            // There will never be more characters than bytes in the files
            char[] text = new char[numbytes]; // to hold file contents
            int p = 0; // current position in the text[] array

            // Loop through the files again, reading their content as text
            for (int i = 0; i < numfiles; i++) {
                File f = (File) filelist.get(i);
                Reader r = new BufferedReader(new FileReader(f));
                p += r.read(text, p, (int) f.length());
            }

            // Convert the character array to a string and wrap it
            // in a pre-defined Transferable class for transferring strings
            StringSelection selection = new StringSelection(new String(text, 0, p));

            // Ask the wrapped handler to import the string
            return wrappedHandler.importData(c, selection);
        }
        // If anything goes wrong, just beep to tell the user
        catch (UnsupportedFlavorException e) {
            c.getToolkit().beep(); // audible error
            return false; // return failure code
        } catch (IOException e) {
            c.getToolkit().beep(); // audible error
            return false; // return failure code
        }
    }

    // Otherwise let the wrapped class handle this transferable itself
    return wrappedHandler.importData(c, t);
}

From source file:net.sf.jabref.gui.fieldeditors.FileListEditorTransferHandler.java

@Override
public boolean importData(JComponent comp, Transferable t) {
    // If the drop target is the main table, we want to record which
    // row the item was dropped on, to identify the entry if needed:

    try {/*from w  w w . ja  v a  2s.c o  m*/

        List<File> files = new ArrayList<>();
        // This flavor is used for dragged file links in Windows:
        if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            files.addAll((List<File>) t.getTransferData(DataFlavor.javaFileListFlavor));
        }

        if (t.isDataFlavorSupported(urlFlavor)) {
            URL dropLink = (URL) t.getTransferData(urlFlavor);
            LOGGER.debug("URL: " + dropLink);
        }

        // This is used when one or more files are pasted from the file manager
        // under Gnome. The data consists of the file paths, one file per line:
        if (t.isDataFlavorSupported(stringFlavor)) {
            String dropStr = (String) t.getTransferData(stringFlavor);
            files.addAll(EntryTableTransferHandler.getFilesFromDraggedFilesString(dropStr));
        }

        SwingUtilities.invokeLater(() -> {
            for (File file : files) {
                // Find the file's extension, if any:
                String name = file.getAbsolutePath();
                FileUtil.getFileExtension(name).ifPresent(extension -> ExternalFileTypes.getInstance()
                        .getExternalFileTypeByExt(extension).ifPresent(fileType -> {
                            if (droppedFileHandler == null) {
                                droppedFileHandler = new DroppedFileHandler(frame, frame.getCurrentBasePanel());
                            }
                            droppedFileHandler.handleDroppedfile(name, fileType, entryContainer.getEntry());
                        }));
            }
        });
        if (!files.isEmpty()) {
            // Found some files, return
            return true;
        }
    } catch (IOException ioe) {
        LOGGER.warn("Failed to read dropped data. ", ioe);
    } catch (UnsupportedFlavorException | ClassCastException ufe) {
        LOGGER.warn("Drop type error. ", ufe);
    }

    // all supported flavors failed
    StringBuilder logMessage = new StringBuilder("Cannot transfer input:");
    DataFlavor[] inflavs = t.getTransferDataFlavors();
    for (DataFlavor inflav : inflavs) {
        logMessage.append(' ').append(inflav);
    }
    LOGGER.warn(logMessage.toString());

    return false;
}

From source file:com.mirth.connect.client.ui.editors.JavaScriptEditorDialog.java

public void drop(DropTargetDropEvent dtde) {
    try {/*  w ww .  j av  a2 s.c om*/
        Transferable tr = dtde.getTransferable();
        if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {

            dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

            java.util.List fileList = (java.util.List) tr.getTransferData(DataFlavor.javaFileListFlavor);
            Iterator iterator = fileList.iterator();
            while (iterator.hasNext()) {
                File file = (File) iterator.next();

                scriptContent.setText(
                        scriptContent.getText() + FileUtils.readFileToString(file, UIConstants.CHARSET));
            }
        }
    } catch (Exception e) {
        dtde.rejectDrop();
    }
}

From source file:com.mirth.connect.client.ui.components.ChannelTableTransferHandler.java

@Override
public boolean canImport(TransferSupport support) {
    try {/* ww w .  ja  v  a2 s. c  om*/
        if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            List<File> fileList = (List<File>) support.getTransferable()
                    .getTransferData(DataFlavor.javaFileListFlavor);

            for (File file : fileList) {
                if (!FilenameUtils.isExtension(file.getName(), "xml")) {
                    return false;
                }
            }

            return true;
        } else if (support.isDataFlavorSupported(ChannelTableTransferable.CHANNEL_DATA_FLAVOR)) {
            List<Object> list = (List<Object>) support.getTransferable()
                    .getTransferData(ChannelTableTransferable.CHANNEL_DATA_FLAVOR);

            List<Channel> channels = new ArrayList<Channel>();
            for (Object obj : list) {
                if (obj instanceof Channel) {
                    channels.add((Channel) obj);
                } else {
                    return false;
                }
            }

            if (support.getDropLocation() instanceof JTable.DropLocation) {
                return canMoveChannels(channels, ((JTable.DropLocation) support.getDropLocation()).getRow());
            }
        }
    } catch (Exception e) {
        // Return true anyway until this bug is fixed:
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6759788
        return true;
    }

    return false;
}

From source file:org.feistymeow.dragdrop.ListTransferable.java

/**
 * using the set of files that we've been handed, we can do transfers using our two supported
 * flavors./*from  ww w  .  j  a va 2 s .  c om*/
 */
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, java.io.IOException {
    if (flavor == null)
        return null;
    if (size() == 0) {
        logger.debug("size was zero, so loading data just in time");
        boolean worked = loadDataJustInTime(flavor);
        if (!worked || (size() == 0)) {
            logger.warn("failed to retrieve data just in time for getTransferData.");
            return null;
        }
    }
    // help from workaround at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4899516
    logger.debug("responding to flavor: " + flavor.toString());
    if (flavor.equals(DataFlavor.javaFileListFlavor)) {
        logger.debug("java file list flavor...");
        List<Object> data = new java.util.ArrayList<Object>();
        data.addAll(this);
        return data;
    } else if (flavor.equals(URIListFlavor) || flavor.equals(AltURIListFlavor)) {
        logger.debug("uri list flavor...");
        StringBuilder data = new StringBuilder();
        Iterator<Object> iter = iterator();
        while (iter.hasNext()) {
            Object x = iter.next();
            if (x instanceof File) {
                File elem = (File) x;
                data.append(elem.toURI() + "\r\n");
            } else if (x instanceof String) {
                data.append((String) x + "\r\n");
            } else {
                logger.debug("did not know how to handle type in transfer: " + x.toString());
            }
        }
        logger.debug("returning URI string: " + data.toString());
        return data.toString();
    } else {
        logger.debug("getTransferData: didn't know how to handle the requested flavor.");
        throw new UnsupportedFlavorException(flavor);
    }
}

From source file:pl.otros.logview.gui.Log4jPatternParserEditor.java

private void enableDragAndDrop() {
    logFileContent.setDragEnabled(true);
    final TransferHandler defaultTransferHandler = logFileContent.getTransferHandler();
    TransferHandler transferHandler = new TransferHandler() {

        @Override//  www  .  j a  v a2  s  . c  om
        public boolean importData(TransferSupport support) {
            if (isText(support)) {
                try {
                    String transferData = (String) support.getTransferable()
                            .getTransferData(DataFlavor.stringFlavor);
                    if (transferData.startsWith("file://")) {
                        String firstLine = transferData;
                        if (firstLine.indexOf('\n') > 0) {
                            firstLine = firstLine.substring(0, firstLine.indexOf('\n') - 1);
                        }
                        loadLogContent(VFS.getManager().resolveFile(firstLine));
                    } else {
                        defaultTransferHandler.importData(support);
                    }
                    return true;

                } catch (UnsupportedFlavorException e) {
                    LOGGER.warning("Can't import data, UnsupportedFlavorException: " + e.getMessage());
                } catch (IOException e) {
                    LOGGER.warning("Can't import data, IOException: " + e.getMessage());
                }
            }

            if (isListOfFiles(support)) {
                try {
                    List data = (List) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                    if (data.size() > 0) {
                        File file = (File) data.get(0);
                        loadLogContent(VFS.getManager().resolveFile(file.getAbsolutePath()));
                        return true;
                    }
                } catch (UnsupportedFlavorException e) {
                    LOGGER.warning("Can't import data, UnsupportedFlavorException: " + e.getMessage());
                } catch (IOException e) {
                    LOGGER.warning("Can't import data, IOException: " + e.getMessage());
                }
            }

            return defaultTransferHandler.importData(support);
        }

        @Override
        public boolean canImport(TransferSupport support) {
            if (isText(support) || isListOfFiles(support)) {
                return true;
            }
            return defaultTransferHandler.canImport(support);
        }

        private boolean isListOfFiles(TransferSupport support) {
            return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
        }

        private boolean isText(TransferSupport support) {
            return DataFlavor.selectBestTextFlavor(support.getDataFlavors()) != null;
        }

    };
    logFileContent.setTransferHandler(transferHandler);
    loadLog.setTransferHandler(transferHandler);
    logFileContentLabel.setTransferHandler(transferHandler);
}

From source file:com.mirth.connect.client.ui.TemplatePanel.java

public void dragEnter(DropTargetDragEvent dtde) {
    try {//from  w w w .  j av a  2  s.  c o m
        Transferable tr = dtde.getTransferable();

        if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
            List<File> fileList = (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor);
            Iterator<File> iterator = fileList.iterator();

            while (iterator.hasNext()) {
                iterator.next();
            }
        } else {
            dtde.rejectDrag();
        }
    } catch (Exception e) {
        dtde.rejectDrag();
    }
}