Example usage for java.awt.datatransfer DataFlavor stringFlavor

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

Introduction

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

Prototype

DataFlavor stringFlavor

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

Click Source Link

Document

The DataFlavor representing a Java Unicode String class, where:
 representationClass = java.lang.String mimeType            = "application/x-java-serialized-object" 

Usage

From source file:com._17od.upm.gui.AccountDialog.java

/**
 * This method takes in a JTextArea object and then inserts the contents of
 * the system clipboard into that text area at the cursor position.
 * //w ww . java 2  s. c o m
 * @param textArea
 */
public void pasteToTextArea(JTextArea textArea) {
    String text = "";
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable clipText = clipboard.getContents(null);
    if ((clipText != null) && clipText.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            text = (String) clipText.getTransferData(DataFlavor.stringFlavor);
        } catch (UnsupportedFlavorException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    textArea.insert(text, textArea.getCaretPosition());
    textArea.requestFocus();
}

From source file:de.tor.tribes.ui.views.DSWorkbenchDoItYourselfAttackPlaner.java

private void copyFromInternalClipboard() {
    try {//from www  .j ava  2  s  .c o  m
        String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null)
                .getTransferData(DataFlavor.stringFlavor);

        String[] lines = data.split("\n");
        int cnt = 0;
        AttackManager.getSingleton().invalidate();
        for (String line : lines) {
            Attack a = Attack.fromInternalRepresentation(line);
            if (a != null) {
                AttackManager.getSingleton().addManagedElement(AttackManager.MANUAL_ATTACK_PLAN, a);
                cnt++;
            }
        }
        showSuccess(cnt + ((cnt == 1) ? " Angriff eingefgt" : " Angriffe eingefgt"));
    } catch (UnsupportedFlavorException | IOException ufe) {
        logger.error("Failed to copy attacks from internal clipboard", ufe);
        showError("Fehler beim Einfgen der Angriffe");
    }
    ((DoItYourselfAttackTableModel) jAttackTable.getModel()).fireTableDataChanged();
    AttackManager.getSingleton().revalidate();
}

From source file:de.tor.tribes.ui.algo.AttackTimePanel.java

@Override
public void drop(DropTargetDropEvent dtde) {
    if (dtde.getDropTargetContext().getComponent().equals(jTimeFrameList)) {
        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
        try {/*  ww w.  j a  va 2s  .  c  om*/
            String data = (String) dtde.getTransferable().getTransferData(DataFlavor.stringFlavor);
            TimeSpan s = TimeSpan.fromPropertyString(data);
            if (s == null) {
                throw new UnsupportedFlavorException(DataFlavor.stringFlavor);
            }
            addTimeSpan(s);
        } catch (UnsupportedFlavorException | IOException usfe) {
            //invalid data
        }
    }
}

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 a  va  2  s . c o  m
            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:com.emental.mindraider.ui.frames.MindRaiderMainWindow.java

public void drop(DropTargetDropEvent evt) {
    logger.debug("=-> drop");

    try {/*from ww w .  j  av  a  2  s .  c  om*/
        Transferable t = evt.getTransferable();

        if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            logger.debug(" Accepting 'string' data flavor...");
            evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            String s = (String) t.getTransferData(DataFlavor.stringFlavor);
            evt.getDropTargetContext().dropComplete(true);

            logger.debug("DnD: '" + s + "'");
            if (s != null) {
                int indexOf = s.indexOf("\n");
                if (indexOf != -1) {
                    dragAndDropReference = new DragAndDropReference(s.substring(indexOf + 1),
                            s.substring(0, indexOf), DragAndDropReference.BROWSER_LINK);
                } else {
                    dragAndDropReference = new DragAndDropReference(s, DragAndDropReference.BROWSER_LINK);
                }
            }
        } else {
            if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                logger.debug(" Accepting 'file list' data flavor...");
                evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                List<Object> list = (List<Object>) t.getTransferData(DataFlavor.javaFileListFlavor);
                if (list != null) {
                    Iterator<Object> iterator = list.iterator();
                    while (iterator.hasNext()) {
                        Object next = iterator.next();
                        if (next instanceof File) {
                            logger.debug(" DnD file: " + next);
                            dragAndDropReference = new DragAndDropReference(((File) next).getAbsolutePath(),
                                    DragAndDropReference.EXPLORER_LINK);
                        }
                    }
                }
            } else {
                logger.debug("DnD rejected! ");
                dragAndDropReference = null;

                // DataFlavor[] dfs=t.getTransferDataFlavors();
                // for (int i = 0; i < dfs.length; i++) {
                // logger.debug(" "+i+" ... "+dfs[i].getMimeType());
                // logger.debug(" "+i+" ...
                // "+dfs[i].getDefaultRepresentationClassAsString());
                // logger.debug(" "+i+" ...
                // "+dfs[i].getHumanPresentableName());
                // }
            }
        }
    } catch (Exception e) {
        logger.debug("Drag&Drop error:", e);
        dragAndDropReference = null;
    }

    OutlineJPanel.getInstance().enableDisableAttachToolbarButton();

    if (dragAndDropReference != null) {
        JOptionPane.showMessageDialog(this,
                "Dropped local/web resource reference stored! Use \n'clip' icon from Notebook outline toolbar to attach it.",
                "Drag&Drop Info", JOptionPane.INFORMATION_MESSAGE);

        dragAndDropReference.debug();
    }
    logger.debug("<-= drop");
}

From source file:kolacer.Kolacer.java

private String stringZeSchranky() {
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable t = c.getContents(this);
    if (t == null)
        return null;
    try {/*from w  ww.j av a2s .c o  m*/
        return ((String) t.getTransferData(DataFlavor.stringFlavor));
    } catch (UnsupportedFlavorException | IOException e) {
        System.err.println(e.getMessage());
        return "Chyba pi ?ten ze schrnky";
    } //try
}

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;/*  w  ww .j a va2  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:cz.muni.fi.pv168.MainForm.java

private void Paste() {
    Clipboard clipboard = getToolkit().getSystemClipboard();
    String data = null;//from  ww w.  j a v a  2  s. c  o m

    try {
        data = (String) clipboard.getData(DataFlavor.stringFlavor);
    } catch (IOException | UnsupportedFlavorException e) {
        return;
    }

    if (data == null) {
        return;
    }

    switch (jTabbedPane1.getSelectedIndex()) {
    case 0: {
        int column = carTable.getSelectedColumn();
        int row = carTable.getSelectedRow();

        CarsTableModel ctm = (CarsTableModel) carTable.getModel();

        if ((column < 0) || (row < 0) || !ctm.isCellEditable(row, column)) {
            return;
        }

        ctm.setValueAt(data, row, column);

        break;
    }
    case 1: {
        int column = customerTable.getSelectedColumn();
        int row = customerTable.getSelectedRow();

        CustomersTableModel ctm = (CustomersTableModel) customerTable.getModel();

        if ((column < 0) || (row < 0) || !ctm.isCellEditable(row, column)) {
            return;
        }

        ctm.setValueAt(data, row, column);

        break;
    }
    case 2: {
        int column = rentTable.getSelectedColumn();
        int row = rentTable.getSelectedRow();

        RentsTableModel rtm = (RentsTableModel) rentTable.getModel();

        if ((column < 0) || (row < 0) || !rtm.isCellEditable(row, column)) {
            return;
        }

        rtm.setValueAt(data, row, column);

        break;
    }
    default:
        break;
    }
}

From source file:com.virtusa.isq.rft.runtime.RFTCommandBase.java

/**
 * Get the selected text in webpage to the clipboard and compare the value
 * with the given input.//from   ww w.  java2 s.  com
 * 
 * @param value
 *            the value
 * @throws Exception
 *             the exception
 */

private void fireEventVerifyValue(final String value) throws Exception {

    String clipBoardText = "";
    Robot robot = new Robot();

    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_C);
    robot.keyRelease(KeyEvent.VK_C);
    robot.keyRelease(KeyEvent.VK_CONTROL);

    Utils.pause(retryInterval);
    Transferable trans = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

    try {
        if (trans != null) {
            clipBoardText = (String) trans.getTransferData(DataFlavor.stringFlavor);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (clipBoardText.equals(value)) {

        reportResults(ReportLogger.ReportLevel.SUCCESS, "Fire Event", "Success",
                "Verify value passed. Value : " + value);

    } else {

        reportResults(true, ReportLogger.ReportLevel.FAILURE, "Fire Event", "Error",
                "Verify value match expected. ::: " + "Expected value : " + value + " Actual value : "
                        + clipBoardText);
    }
}

From source file:canreg.client.gui.dataentry.PDSEditorInternalFrame.java

private void pdsTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdsTableMouseReleased
    if (evt.isPopupTrigger()) {
        copyMenuItem.setEnabled(!pdsTable.getSelectionModel().isSelectionEmpty());
        Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this);
        pasteMenuItem.setEnabled(contents.isDataFlavorSupported(DataFlavor.stringFlavor));
        tablePopupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
    }/*w w w. j a  va  2 s. co  m*/
}