Example usage for java.awt.datatransfer Transferable getTransferData

List of usage examples for java.awt.datatransfer Transferable getTransferData

Introduction

In this page you can find the example usage for java.awt.datatransfer Transferable getTransferData.

Prototype

public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException;

Source Link

Document

Returns an object which represents the data to be transferred.

Usage

From source file:UTest.java

public boolean importData(JComponent src, Transferable transferable) {
    // Ok, here's the tricky part...
    println("Receiving data from " + src);
    println("Transferable object is: " + transferable);
    println("Valid data flavors: ");
    DataFlavor[] flavors = transferable.getTransferDataFlavors();
    DataFlavor listFlavor = null;
    DataFlavor objectFlavor = null;
    DataFlavor readerFlavor = null;
    int lastFlavor = flavors.length - 1;

    // Check the flavors and see if we find one we like.
    // If we do, save it.
    for (int f = 0; f <= lastFlavor; f++) {
        println("  " + flavors[f]);
        if (flavors[f].isFlavorJavaFileListType()) {
            listFlavor = flavors[f];// w  w  w .  j  ava2s.c o  m
        }
        if (flavors[f].isFlavorSerializedObjectType()) {
            objectFlavor = flavors[f];
        }
        if (flavors[f].isRepresentationClassReader()) {
            readerFlavor = flavors[f];
        }
    }

    // Ok, now try to display the content of the drop.
    try {
        DataFlavor bestTextFlavor = DataFlavor.selectBestTextFlavor(flavors);
        BufferedReader br = null;
        String line = null;
        if (bestTextFlavor != null) {
            println("Best text flavor: " + bestTextFlavor.getMimeType());
            println("Content:");
            Reader r = bestTextFlavor.getReaderForText(transferable);
            br = new BufferedReader(r);
            line = br.readLine();
            while (line != null) {
                println(line);
                line = br.readLine();
            }
            br.close();
        } else if (listFlavor != null) {
            java.util.List list = (java.util.List) transferable.getTransferData(listFlavor);
            println(list);
        } else if (objectFlavor != null) {
            println("Data is a java object:\n" + transferable.getTransferData(objectFlavor));
        } else if (readerFlavor != null) {
            println("Data is an InputStream:");
            br = new BufferedReader((Reader) transferable.getTransferData(readerFlavor));
            line = br.readLine();
            while (line != null) {
                println(line);
            }
            br.close();
        } else {
            // Don't know this flavor type yet...
            println("No text representation to show.");
        }
        println("\n\n");
    } catch (Exception e) {
        println("Caught exception decoding transfer:");
        println(e);
        return false;
    }
    return true;
}

From source file:zsk.JFCMainClient.java

/**
 * processing event of dropping a HTTP URL, YT-Video Image or plain text (URL) onto the frame
 * /*from w  w  w. j a v a  2 s .c o  m*/
 * seems not to work with M$-IE (8,9) - what a pity!
 */
public void drop(DropTargetDropEvent dtde) {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    DataFlavor fl = null;
    String str = "";

    debugoutput("DataFlavors found: ".concat(Integer.toString(flavors.length)));
    for (int i = 0; i < flavors.length; i++) {
        fl = flavors[i];
        if (fl.isFlavorTextType() /* || fl.isMimeTypeEqual("text/html") || fl.isMimeTypeEqual("application/x-java-url") || fl.isMimeTypeEqual("text/uri-list")*/) {
            try {
                dtde.acceptDrop(dtde.getDropAction());
            } catch (Throwable t) {
            }
            try {
                if (tr.getTransferData(fl) instanceof InputStreamReader) {
                    debugoutput("Text-InputStream");
                    BufferedReader textreader = new BufferedReader((Reader) tr.getTransferData(fl));
                    String sline = "";
                    try {
                        while (sline != null) {
                            sline = textreader.readLine();
                            if (sline != null)
                                str += sline;
                        }
                    } catch (Exception e) {
                    } finally {
                        textreader.close();
                    }
                    str = str.replaceAll("<[^>]*>", ""); // remove HTML tags, especially a hrefs - ignore HTML characters like &szlig; (which are no tags)
                } else if (tr.getTransferData(fl) instanceof InputStream) {
                    debugoutput("Byte-InputStream");
                    InputStream input = new BufferedInputStream((InputStream) tr.getTransferData(fl));
                    int idata = input.read();
                    String sresult = "";
                    while (idata != -1) {
                        if (idata != 0)
                            sresult += new Character((char) idata).toString();
                        idata = input.read();
                    } // while
                    debugoutput("sresult: ".concat(sresult));
                } else {
                    str = tr.getTransferData(fl).toString();
                }
            } catch (IOException ioe) {
            } catch (UnsupportedFlavorException ufe) {
            }

            debugoutput("drop event text: ".concat(str).concat(" (").concat(fl.getMimeType()).concat(") "));
            // insert text into textfield - almost the same as user drops text/url into this field
            // except special characaters -> from http://de.wikipedia.org/wiki/GNU-Projekt (GNU is not Unix)(&bdquo;GNU is not Unix&ldquo;)
            // two drops from same source .. one time in textfield and elsewhere - maybe we change that later?!
            if (str.matches(szYTREGEX.concat("(.*)"))) {
                synchronized (JFCMainClient.frame.textinputfield) {
                    JFCMainClient.frame.textinputfield
                            .setText(str.concat(JFCMainClient.frame.textinputfield.getText()));
                }
                debugoutput("breaking for-loop with str: ".concat(str));
                break;
            }
        } else {
            String sv = "drop event unknown type: ".concat(fl.getHumanPresentableName());
            //output(sv);
            debugoutput(sv);
        }
    } // for

    dtde.dropComplete(true);
}

From source file:com.SE.myPlayer.MusicPlayerGUI.java

public void tableReferesh(JTable songData_Table, String tableName, String columName) {
        int emptyResultSet = 0;

        try {//from w w w  .j  ava 2 s.com
            con = db.getCon();
            stmt = con.createStatement();
            ResultSet rs;

            switch (tableName) {
            case "library":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            case "playlist":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            default:
                rs = stmt.executeQuery(
                        "Select library.id_songs, library.song_location, library.song_name, library.song_album, library.song_artist, library.genre, library.year, library.time, library.comment from playlist INNER JOIN library ON library.id_songs = playlist.id_songs AND playlist.playlist_name = '"
                                + tableName + "' order by " + columName + "");
                break;
            }

            DefaultTableModel myModel = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };

            String[] songsColumnsName = { "Location", "Name", "Album", "Artist", "Genre", "Year", "Time",
                    "Comment" };
            myModel.setColumnIdentifiers(songsColumnsName);

            ResultSetMetaData rsmd = rs.getMetaData();
            int colNumbers = rsmd.getColumnCount();

            Object[] objects = new Object[colNumbers];

            while (rs.next()) {
                emptyResultSet = 1;
                for (int i = 0; i < colNumbers - 1; i++) {
                    objects[i] = rs.getObject(i + 2);
                }
                myModel.addRow(objects);
            }

            if (emptyResultSet == 0) {
                myModel.addRow(objects);
            }

            songData_Table.setModel(myModel);

            rs = stmt.executeQuery("select col_name from col_name where col_status = 0");

            while (rs.next()) {
                songData_Table.removeColumn(songData_Table.getColumn(rs.getString(1)));
            }

            songData_Table.getTableHeader().removeMouseListener(ma);
            songData_Table.getTableHeader().addMouseListener(ma);
            songData_Table.setDragEnabled(true);
            songData_Table.setDropTarget(new DropTarget() {
                @Override
                public synchronized void drop(DropTargetDropEvent dtde) {

                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    Transferable t = dtde.getTransferable();

                    try {
                        if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.javaFileListFlavor);
                            String files = fileList.toString();
                            finalString = convertFileString(files);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        } else if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.stringFlavor);
                            String fileListString = fileList.toString();

                            fileListString = Arrays.toString(fileListString.split("\\n"));

                            String[] splitLocations = fileListString.split(",\\s");

                            for (int i = 0; i < splitLocations.length; i++) {
                                if (i == 0) {
                                    splitLocations[i] = splitLocations[i].substring(1,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                } else {
                                    splitLocations[i] = splitLocations[i].substring(0,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                }
                            }

                            for (int i = 0; i < splitLocations.length; i++) {
                                splitLocations[i] = sd.getLocations(splitLocations[i]);
                            }
                            finalString = Arrays.asList(splitLocations);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        }
                    } catch (UnsupportedFlavorException | IOException | InvalidDataException
                            | UnsupportedTagException ex) {
                        System.out.println("Error in second drop flavour............" + ex);
                    }
                }
            });

            if (con != null) {
                stmt.close();
                con.close();
            }
        } catch (SQLException e) {
            System.out.println("Error in Stmt " + e);
        }
    }

From source file:org.rdv.datapanel.DigitalTabularDataPanel.java

/**
 * an overridden method from//  w w  w .ja v  a 2s  . c o  m
 * 
 * @see org.rdv.datapanel.AbstractDataPanel for the
 * @see DropTargetListener interface
 */
@SuppressWarnings("unchecked")
public void drop(DropTargetDropEvent e) {
    try {
        int dropAction = e.getDropAction();
        if (dropAction == DnDConstants.ACTION_LINK) {
            DataFlavor channelListDataFlavor = new ChannelListDataFlavor();
            Transferable tr = e.getTransferable();
            if (e.isDataFlavorSupported(channelListDataFlavor)) {
                e.acceptDrop(DnDConstants.ACTION_LINK);
                e.dropComplete(true);

                // calculate which table the x coordinate of the mouse
                // corresponds to
                double clickX = e.getLocation().getX(); // get the mouse x
                // coordinate
                int compWidth = dataComponent.getWidth(); // gets the
                // width of this
                // component
                final int tableNum = (int) (clickX * columnGroupCount / compWidth);

                final List<String> channels = (List) tr.getTransferData(channelListDataFlavor);

                new Thread() {
                    public void run() {
                        for (int i = 0; i < channels.size(); i++) {
                            String channel = channels.get(i);
                            boolean status;
                            if (supportsMultipleChannels()) {
                                status = addChannel(channel, tableNum);
                            } else {
                                status = setChannel(channel);
                            }

                            if (!status) {
                                // TODO display an error in the UI
                            }
                        }
                    }
                }.start();
            } else {
                e.rejectDrop();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (UnsupportedFlavorException ufe) {
        ufe.printStackTrace();
    }
}

From source file:javazoom.jlgui.player.amp.Player.java

/**
 * DnD : Drop implementation.//from www . j a  va 2s . com
 * Adds all dropped files to the playlist.
 */
public void drop(DropTargetDropEvent e) {
    // Check DataFlavor
    DataFlavor[] dfs = e.getCurrentDataFlavors();
    DataFlavor tdf = null;
    for (int i = 0; i < dfs.length; i++) {
        if (DataFlavor.javaFileListFlavor.equals(dfs[i])) {
            tdf = dfs[i];
            break;
        }
    }
    // Is file list ?
    if (tdf != null) {
        // Accept COPY DnD only.
        if ((e.getSourceActions() & DnDConstants.ACTION_COPY) != 0) {
            e.acceptDrop(DnDConstants.ACTION_COPY);
        } else
            return;
        try {
            Transferable t = e.getTransferable();
            Object data = t.getTransferData(tdf);
            // How many files ?
            if (data instanceof java.util.List) {
                java.util.List al = (java.util.List) data;
                // Read the first File.
                if (al.size() > 0) {
                    File file = null;
                    // Stops the player if needed.
                    if ((playerState == PLAY) || (playerState == PAUSE)) {
                        theSoundPlayer.stop();
                        playerState = STOP;
                    }
                    // Clean the playlist.
                    playlist.removeAllItems();
                    // Add all dropped files to playlist.
                    ListIterator li = al.listIterator();
                    while (li.hasNext()) {
                        file = (File) li.next();
                        PlaylistItem pli = null;
                        if (file != null) {

                            pli = new PlaylistItem(file.getName(), file.getAbsolutePath(), -1, true);
                            if (pli != null)
                                playlist.appendItem(pli);
                        }
                    }
                    // Start the playlist from the top.
                    playlist.nextCursor();
                    fileList.initPlayList();
                    this.setCurrentSong(playlist.getCursor());
                }
            } else {
                log.info("Unknown dropped objects");
            }
        } catch (IOException ioe) {
            log.info("Drop error", ioe);
            e.dropComplete(false);
            return;
        } catch (UnsupportedFlavorException ufe) {
            log.info("Drop error", ufe);
            e.dropComplete(false);
            return;
        } catch (Exception ex) {
            log.info("Drop error", ex);
            e.dropComplete(false);
            return;
        }
        e.dropComplete(true);
    }
}

From source file:ded.ui.DiagramController.java

/** Try to read the clipboard contents as a Diagram.  Return null and
  * display an error if we cannot. */
private Diagram getClipboardAsDiagram() {
    // Let's start with the "selection" because if it is valid JSON
    // then it's probably what we want.
    String selErrorMessage = null;
    String selContents = null;/*from w w  w.j  ava2  s.  co m*/
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemSelection();
    if (clipboard == null) {
        // Probably we're running on something other than X Windows,
        // so we thankfully don't have to deal with the screwy
        // "selection" concept.
    } else {
        Transferable clipData = clipboard.getContents(clipboard);
        if (clipData == null) {
            selErrorMessage = "Nothing is in the \"selection\".";
        } else {
            try {
                if (clipData.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    selContents = (String) (clipData.getTransferData(DataFlavor.stringFlavor));

                    // Try to parse it.
                    try {
                        return Diagram.parseJSONString(selContents);
                    } catch (JSONException e) {
                        selErrorMessage = "Could not parse selection data as Diagram JSON: " + e;
                    }
                } else {
                    selErrorMessage = "The data in the selection is not a string.";
                }
            } catch (Exception e) {
                selErrorMessage = "Error while retrieving selection data: " + e;
            }
        }
    }

    // Now try again with the clipboard.
    String clipErrorMessage = null;
    String clipContents = null;
    clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    if (clipboard == null) {
        clipErrorMessage = "getSystemClipboard returned null?!";
    } else {
        Transferable clipData = clipboard.getContents(clipboard);
        if (clipData == null) {
            clipErrorMessage = "Nothing is in the clipboard.";
        } else {
            try {
                if (clipData.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    clipContents = (String) (clipData.getTransferData(DataFlavor.stringFlavor));

                    try {
                        return Diagram.parseJSONString(clipContents);
                    } catch (JSONException e) {
                        clipErrorMessage = "Could not parse clipboard data as Diagram JSON: " + e;
                    }
                } else {
                    clipErrorMessage = "The data in the clipboard is not a string.";
                }
            } catch (Exception e) {
                clipErrorMessage = "Error while retrieving clipboard data: " + e;
            }
        }
    }

    // Both methods failed, and we have one or two error messages.
    // Decide what to show.
    if (selErrorMessage == null) {
        this.errorMessageBox(clipErrorMessage);
    } else if (selContents == null && clipContents != null) {
        this.errorMessageBox(clipErrorMessage);
    } else if (selContents != null && clipContents == null) {
        this.errorMessageBox(selErrorMessage);
    } else if (selContents.equals(clipContents)) {
        this.errorMessageBox(clipErrorMessage + "  (The selection and clipboard contents are the same.)");
    } else {
        this.errorMessageBox("Failed to read either the selection or the clipboard.  " + selErrorMessage + "  "
                + clipErrorMessage);
    }

    return null;
}

From source file:com.pironet.tda.TDA.java

private void getLogfileFromClipboard() {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    String text = null;/*from   ww  w  .  ja  v a  2s. c om*/

    try {
        if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            text = (String) t.getTransferData(DataFlavor.stringFlavor);
        }
    } catch (UnsupportedFlavorException | IOException ex) {
        ex.printStackTrace();
    }

    if (text != null) {
        if (topNodes == null) {
            initDumpDisplay(text);
        } else {
            addDumpStream(new ByteArrayInputStream(text.getBytes()),
                    "Clipboard at " + new Date(System.currentTimeMillis()), false);
            addToLogfile(text);
            if (this.getRootPane() != null) {
                this.getRootPane().revalidate();
            }
            displayContent(null);
        }

        if (!this.runningAsVisualVMPlugin) {
            getMainMenu().getFindLRThreadsToolBarButton().setEnabled(true);
            getMainMenu().getExpandButton().setEnabled(true);
            getMainMenu().getCollapseButton().setEnabled(true);
        }
    }
}

From source file:org.gtdfree.GTDFree.java

protected TrayIcon getTrayIcon() {
    if (trayIcon == null) {
        if (ApplicationHelper.isGTKLaF()) {
            trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_large_tray_splash));
        } else {//from   w w w .j ava  2s .c  om
            trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_small_tray_splash));
        }

        trayIcon.setImageAutoSize(true);
        trayIcon.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    trayIconPopup.setVisible(false);
                    if (getJFrame().isVisible()) {
                        getJFrame().setVisible(false);
                    } else {
                        pushVisible();
                    }
                } else {
                    if (trayIconPopup.isVisible()) {
                        trayIconPopup.setVisible(false);
                    } else {
                        Point p = new Point(e.getPoint());
                        /*
                         * Disabled, because we are anyway doing things like rollover,
                         * which are probably done by Frame.
                        if (getJFrame().isShowing()) {
                           SwingUtilities.convertPointFromScreen(p, getJFrame());
                           trayIconPopup.show(getJFrame(), p.x, p.y);
                        } else {
                        }*/
                        trayIconPopup.show(null, p.x, p.y);
                    }
                }
            }
        });
        trayIcon.setToolTip("GTD-Free - " + Messages.getString("GTDFree.Tray.desc")); //$NON-NLS-1$ //$NON-NLS-2$

        /*
         * Necessary only when popup is showing with null window. Hides popup.
         */
        MouseListener hideMe = new MouseAdapter() {
            @Override
            public void mouseExited(MouseEvent e) {
                if (e.getComponent() instanceof JMenuItem) {
                    JMenuItem jm = (JMenuItem) e.getComponent();
                    jm.getModel().setRollover(false);
                    jm.getModel().setArmed(false);
                    jm.repaint();
                }

                Point p = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), trayIconPopup);
                //System.out.println(p.x+" "+p.y+" "+trayIconPopup.getWidth()+" "+trayIconPopup.getHeight());
                if (p.x < 0 || p.x >= trayIconPopup.getWidth() || p.y < 0 || p.y >= trayIconPopup.getHeight()) {
                    trayIconPopup.setVisible(false);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                if (e.getComponent() instanceof JMenuItem) {
                    JMenuItem jm = (JMenuItem) e.getComponent();
                    jm.getModel().setRollover(true);
                    jm.getModel().setArmed(true);
                    jm.repaint();
                }
            }
        };

        trayIconPopup = new JPopupMenu();
        trayIconPopup.addMouseListener(hideMe);

        JMenuItem mi = new JMenuItem(Messages.getString("GTDFree.Tray.Drop")); //$NON-NLS-1$
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_collecting));
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Drop.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);

        /*
         * Workaround for tray, if JFrame is showing, then mouse click is not fired
         */
        mi.addMouseListener(new MouseAdapter() {
            private boolean click = false;

            @Override
            public void mousePressed(MouseEvent e) {
                click = true;
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (click) {
                    click = false;
                    doMouseClicked(e);
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                click = false;
            }

            private void doMouseClicked(MouseEvent e) {
                trayIconPopup.setVisible(false);
                Clipboard c = null;
                if (e.getButton() == MouseEvent.BUTTON1) {
                    c = Toolkit.getDefaultToolkit().getSystemClipboard();
                } else if (e.getButton() == MouseEvent.BUTTON2) {
                    c = Toolkit.getDefaultToolkit().getSystemSelection();
                } else {
                    return;
                }
                try {
                    Object o = c.getData(DataFlavor.stringFlavor);
                    if (o != null) {
                        getEngine().getGTDModel().collectAction(o.toString());
                    }
                    flashMessage(Messages.getString("GTDFree.Tray.Collect.ok"), e.getLocationOnScreen()); //$NON-NLS-1$
                } catch (Exception e1) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e1); //$NON-NLS-1$
                    flashMessage(Messages.getString("GTDFree.Tray.Collect.fail") + e1.getMessage(), //$NON-NLS-1$
                            e.getLocationOnScreen());
                }
            }
        });

        TransferHandler th = new TransferHandler() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
                return DataFlavor.selectBestTextFlavor(transferFlavors) != null;
            }

            @Override
            public boolean importData(JComponent comp, Transferable t) {
                try {
                    DataFlavor f = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors());
                    Object o = t.getTransferData(f);
                    if (o != null) {
                        getEngine().getGTDModel().collectAction(o.toString());
                    }
                    return true;
                } catch (UnsupportedFlavorException e) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$
                } catch (IOException e) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$
                }
                return false;
            }

        };
        mi.setTransferHandler(th);

        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_delete));
        mi.setText(Messages.getString("GTDFree.Tray.Hide")); //$NON-NLS-1$
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Hide.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                if (getJFrame().isVisible()) {
                    getJFrame().setVisible(false);
                }
            }
        });
        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_splash));
        mi.setText(Messages.getString("GTDFree.Tray.Show")); //$NON-NLS-1$
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Show.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                pushVisible();
            }
        });
        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_exit));
        mi.setText(Messages.getString("GTDFree.Tray.Exit")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                close(false);
            }
        });
        trayIconPopup.add(mi);

    }
    return trayIcon;
}

From source file:tvbrowser.ui.mainframe.MainFrame.java

/**
 * extract the drag and drop targets from the event
 * @param transferable/*w  ww  .  j  a v  a2 s  . c om*/
 * @param dataFlavors
 * @return
 */
private File[] getDragDropPlugins(final DataFlavor[] dataFlavors, final Transferable transferable) {
    HashSet<File> files = new HashSet<File>();
    for (DataFlavor flavor : dataFlavors) {
        try {
            Object data = transferable.getTransferData(flavor);

            if (data instanceof List) {
                for (Object o : ((List) data)) {
                    if (o instanceof File) {
                        addPluginFile((File) o, files);
                    }
                }
                if (!files.isEmpty()) {
                    break;
                }
            } else if (data instanceof String) {
                String name = ((String) data).trim();
                if (name.toLowerCase().endsWith("jar")) {
                    File pluginFile = new File(name);
                    if (pluginFile.canRead()) {
                        addPluginFile(pluginFile, files);
                        if (!files.isEmpty()) {
                            break;
                        }
                    } else {
                        try {
                            URI uri = new URI(name);
                            addPluginFile(new File(uri), files);
                        } catch (URISyntaxException e) { // ignore
                        }
                        if (!files.isEmpty()) {
                            break;
                        }
                    }
                }
            }
        } catch (UnsupportedFlavorException e) { //ignore
        } catch (IOException e) { //ignore
        }
    }
    return files.toArray(new File[files.size()]);
}

From source file:com.declarativa.interprolog.gui.ListenerWindow.java

void handlePrologInputDnD(DropTargetDropEvent dtde) {
    //System.out.println("drop:"+dtde);
    try {/*from www  . j a  va2 s. c o  m*/
        Transferable transferable = dtde.getTransferable();
        /*
         DataFlavor[] flavors = transferable.getTransferDataFlavors();
         for (int f=0;f<flavors.length;f++)
         System.out.println("Flavor:"+flavors[f]);*/
        int action = dtde.getDropAction();
        if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            if (engine.isIdle()) {
                dtde.acceptDrop(action);
                final java.util.List files = (java.util.List) transferable
                        .getTransferData(DataFlavor.javaFileListFlavor);
                dtde.getDropTargetContext().dropComplete(true);
                boolean allPs = true;
                for (int f = 0; f < files.size(); f++) {
                    String filename = ((File) files.get(f)).getName();
                    int dot = filename.lastIndexOf('.');
                    if (!filename.endsWith(".P")) {
                        allPs = false;
                        break;
                    }
                }
                if (!allPs) {
                    errorMessage("All dragged files must be Prolog source files (with a .P extension)");
                } else {
                    prologOutput.append("\nReconsulting " + ((files.size() > 1 ? files.size() + " files...\n"
                            : files.size() + " file...\n")));
                    Runnable r = new Runnable() {
                        public void run() {
                            boolean crashed = false;
                            Toolkit.getDefaultToolkit().sync();
                            for (int f = 0; f < files.size() && !crashed; f++) {
                                File file = (File) files.get(f);
                                if (!processDraggedFile(file)) {
                                    crashed = true;
                                }
                            }
                            if (crashed) {
                                prologOutput.append("...terminated with errors.\n");
                            } else {
                                prologOutput.append("...done.\n");
                            }
                        }
                    };
                    SwingUtilities.invokeLater(r);
                }
            } else {
                dtde.rejectDrop();
                errorMessage("You can not consult files while Prolog is working");
            }
        } else {
            dtde.rejectDrop();
        }
    } catch (Exception e) {
        throw new IPException("Problem dropping:" + e);
    }
}