Example usage for java.awt.datatransfer StringSelection StringSelection

List of usage examples for java.awt.datatransfer StringSelection StringSelection

Introduction

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

Prototype

public StringSelection(String data) 

Source Link

Document

Creates a Transferable capable of transferring the specified String .

Usage

From source file:org.syncany.gui.util.DesktopUtil.java

/**
 * Copies the given text to the user clipboard.
 *///from w  w  w.j a  v a2 s. c o m
public static void copyToClipboard(String copyText) {
    StringSelection applicationLinkStringSelection = new StringSelection(copyText);

    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(applicationLinkStringSelection, applicationLinkStringSelection);
}

From source file:org.kontalk.view.Utils.java

static WebMenuItem createCopyMenuItem(final String copyText, String toolTipText) {
    WebMenuItem item = new WebMenuItem(Tr.tr("Copy"));
    if (!toolTipText.isEmpty())
        item.setToolTipText(toolTipText);
    item.addActionListener(new ActionListener() {
        @Override/*from w  ww.  j  a  v  a 2  s. c  om*/
        public void actionPerformed(ActionEvent event) {
            Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
            clip.setContents(new StringSelection(copyText), null);
        }
    });
    return item;
}

From source file:net.pandoragames.far.ui.swing.component.UndoHistoryPopupMenu.java

private void init(SwingConfig config, ComponentRepository componentRepository) {
    // COPY//from  www . j a  v  a 2 s  .  co  m
    JMenuItem copy = new JMenuItem(config.getLocalizer().localize("label.copy"));
    copy.setAccelerator(KeyStroke.getKeyStroke("control C"));
    copy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String selection = textComponent.getSelectedText();
            if (selection != null) {
                StringSelection textTransfer = new StringSelection(selection);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(textTransfer, null);
            }
        }
    });
    this.add(copy);
    // PASTE
    JMenuItem paste = new JMenuItem(config.getLocalizer().localize("label.paste"));
    paste.setAccelerator(KeyStroke.getKeyStroke("control V"));
    paste.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            Transferable transfer = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

            try {
                if (transfer != null && transfer.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    String text = (String) transfer.getTransferData(DataFlavor.stringFlavor);
                    String selected = textComponent.getSelectedText();
                    if (selected == null) {
                        int insertAt = textComponent.getCaretPosition();
                        textComponent.getDocument().insertString(insertAt, text, null);
                    } else {
                        int start = textComponent.getSelectionStart();
                        int end = textComponent.getSelectionEnd();
                        textComponent.getDocument().remove(start, end - start);
                        textComponent.getDocument().insertString(start, text, null);
                    }
                }
            } catch (UnsupportedFlavorException e) {
                LogFactory.getLog(this.getClass()).error("UnsupportedFlavorException reading from clipboard",
                        e);
            } catch (IOException iox) {
                LogFactory.getLog(this.getClass()).error("IOException reading from clipboard", iox);
            } catch (BadLocationException blx) {
                LogFactory.getLog(this.getClass()).error("BadLocationException reading from clipboard", blx);
            }
        }
    });
    this.add(paste);
    // UNDO
    Action undoAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_UNDO);
    if (undoAction != null) {
        undoAction.putValue(Action.NAME, config.getLocalizer().localize("label.undo"));
        this.add(undoAction);
    }
    // REDO
    Action redoAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_REDO);
    if (redoAction != null) {
        redoAction.putValue(Action.NAME, config.getLocalizer().localize("label.redo"));
        this.add(redoAction);
    }
    // PREVIOUS
    Action prevAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_PREVIOUS);
    if (prevAction != null) {
        prevAction.putValue(Action.NAME, config.getLocalizer().localize("label.previous"));
        this.add(prevAction);
    }
    // NEXT
    Action nextAction = textComponent.getActionMap().get(UndoHistory.ACTION_KEY_NEXT);
    if (nextAction != null) {
        nextAction.putValue(Action.NAME, config.getLocalizer().localize("label.next"));
        this.add(nextAction);
    }
}

From source file:com.photon.phresco.framework.actions.FrameworkBaseAction.java

public void copyToClipboard() {
    S_LOGGER.debug("Entered FrameworkBaseAction.copyToClipboard");
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(//from   w  w w.j a v a2 s.c om
            new StringSelection(copyToClipboard.replaceAll(" ", "").replaceAll("(?m)^[ \t]*\r?\n", "")), null);

}

From source file:cz.babi.desktop.remoteme.common.Controller.java

/**
 * Simulate clipboard./*from w  w  w . j  a v a2s .  co  m*/
 * @param character Character to paste from clipboard.
 */
public void keyClipboard(String addInfo) {
    if (Common.DEBUG)
        LOGGER.debug("[keyClipboard][" + addInfo + "]");

    StringSelection stringSelection = new StringSelection(addInfo);
    clipboard.setContents(stringSelection, clipboardOwner);

    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
}

From source file:com.hp.alm.ali.idea.ui.editor.field.HTMLAreaField.java

public static void enableCapability(final JTextPane desc, Project project, String value, boolean editable,
        boolean navigation) {
    value = removeSmallFont(value);/* ww w. j  a  v  a 2  s .c  om*/
    HTMLEditorKit kit = new HTMLLetterWrappingEditorKit();
    desc.setEditorKit(kit);
    desc.setDocument(kit.createDefaultDocument());
    if (!editable && navigation) {
        value = NavigationDecorator.explodeHtml(project, value);
    }
    desc.setText(value);
    if (!editable) {
        desc.setCaret(new NonAdjustingCaret());
    }
    desc.addCaretListener(new BodyLimitCaretListener(desc));
    if (editable) {
        String element = checkElements(desc.getDocument().getDefaultRootElement());
        if (element != null) {
            desc.setToolTipText("Found unsupported element '" + element + "', editing is disabled.");
            editable = false;
        }
    }
    desc.setEditable(editable);

    if (editable && SpellCheckerManager.isAvailable()
            && ApplicationManager.getApplication().getComponent(AliConfiguration.class).spellChecker) {
        desc.getDocument().addDocumentListener(new SpellCheckDocumentListener(project, desc));
    }

    Font font = UIManager.getFont("Label.font");
    String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize()
            + "pt; }";
    ((HTMLDocument) desc.getDocument()).getStyleSheet().addRule(bodyRule);

    // AGM uses plain "p" to create lines, we need to avoid excessive spacing this by default creates
    String paragraphRule = "p { margin-top: 0px; }";
    ((HTMLDocument) desc.getDocument()).getStyleSheet().addRule(paragraphRule);

    Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
    new AnAction() {
        public void actionPerformed(AnActionEvent e) {
            // following is needed to make copy work in the IDE
            try {
                StringSelection selection = new StringSelection(desc.getText(desc.getSelectionStart(),
                        desc.getSelectionEnd() - desc.getSelectionStart()));
                CopyPasteManager.getInstance().setContents(selection);
            } catch (Exception ex) {
                // no clipboard, so what
            }
        }
    }.registerCustomShortcutSet(new CustomShortcutSet(keymap.getShortcuts(IdeActions.ACTION_COPY)), desc);
    new AnAction() {
        public void actionPerformed(AnActionEvent e) {
            // avoid pasting non-supported HTML markup by always converting to plain text
            Transferable contents = CopyPasteManager.getInstance().getContents();
            try {
                desc.getActionMap().get(DefaultEditorKit.cutAction).actionPerformed(null);
                desc.getDocument().insertString(desc.getSelectionStart(),
                        (String) contents.getTransferData(DataFlavor.stringFlavor), null);
            } catch (Exception ex) {
                // no clipboard, so what
            }
        }
    }.registerCustomShortcutSet(new CustomShortcutSet(keymap.getShortcuts(IdeActions.ACTION_PASTE)), desc);
    installNavigationShortCuts(desc);

}

From source file:com.jk.util.JKStringUtil.java

/**
 * Copy to clipboard./*ww w. j a v  a  2 s .c  o  m*/
 *
 * @param text
 *            the text
 */
public static void copyToClipboard(String text) {
    final StringSelection stringSelection = new StringSelection(text);
    final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, stringSelection);
}

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 w ww  .  j  a va  2s.c om
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:phex.gui.dialogs.AboutDialog.java

/**
 * /*from w w w.  j a  va2  s . c  o  m*/
 */
private void prepareComponent() {
    CloseEventHandler closeEventHandler = new CloseEventHandler();
    addWindowListener(closeEventHandler);

    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel contentPanel = new JPanel();
    //JPanel contentPanel = new FormDebugPanel();
    contentPane.add(contentPanel, BorderLayout.CENTER);

    CellConstraints cc = new CellConstraints();
    FormLayout layout = new FormLayout("4dlu, fill:d:grow, 4dlu", // columns
            "p, p, 2dlu, p, 4dlu, p, 4dlu"); //row
    PanelBuilder contentPB = new PanelBuilder(layout, contentPanel);

    Object[] objArr = { PrivateNetworkConstants.PRIVATE_BUILD_ID + VersionUtils.getProgramVersion(),
            VersionUtils.getBuild() };
    DialogBanner banner = new DialogBanner("Phex",
            Localizer.getFormatedString("AboutPhex_VersionInfo", objArr));
    contentPB.add(banner, cc.xywh(1, 1, 3, 1));

    contentPB.add(new JSeparator(), cc.xywh(1, 2, 3, 1));

    JTabbedPane tabbedPane = new JTabbedPane();
    contentPB.add(tabbedPane, cc.xy(2, 4));

    JButton closeBtn = new JButton(Localizer.getString("Close"));
    closeBtn.addActionListener(closeEventHandler);
    contentPB.add(ButtonBarFactory.buildCloseBar(closeBtn), cc.xy(2, 6));

    JPanel aboutPanel = new JPanel();
    layout = new FormLayout("4dlu, fill:d:grow, 4dlu", // columns
            "4dlu, p, 4dlu"); //row
    PanelBuilder aboutPB = new PanelBuilder(layout, aboutPanel);
    tabbedPane.addTab(Localizer.getString("AboutPhex_About"), aboutPanel);

    Object[] objArr2 = { Res.getStr("Program.Url") };
    HTMLMultiLinePanel aboutHtml = new HTMLMultiLinePanel(
            Localizer.getFormatedString("AboutPhex_AboutText", objArr2));
    aboutPB.add(aboutHtml, cc.xy(2, 2));

    JPanel envPanel = new JPanel();
    layout = new FormLayout("2dlu, fill:d:grow, 2dlu", // columns
            "2dlu, p, 2dlu, p, 2dlu"); //row
    PanelBuilder envPB = new PanelBuilder(layout, envPanel);
    tabbedPane.addTab(Localizer.getString("AboutPhex_Environment"), envPanel);

    environmentInfo = new JTextArea(12, 55);
    environmentInfo.setEditable(false);
    envPB.add(new JScrollPane(environmentInfo), cc.xy(2, 2));

    StringBuffer envTextBuffer = new StringBuffer();
    Properties pros = System.getProperties();
    ArrayList<String> list = new ArrayList(pros.keySet());
    Collections.sort(list);
    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        String value = (String) pros.get(key);
        envTextBuffer.append(key).append(" = ").append(value).append(SystemUtils.LINE_SEPARATOR);
    }
    environmentInfo.setText(envTextBuffer.toString());
    environmentInfo.setCaretPosition(0);

    JButton copyBtn = new JButton(Localizer.getString("Copy"));
    copyBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Toolkit.getDefaultToolkit().getSystemClipboard()
                    .setContents(new StringSelection(environmentInfo.getText()), null);
        }
    });
    envPB.add(ButtonBarFactory.buildLeftAlignedBar(copyBtn), cc.xy(2, 4));

    pack();
    setLocationRelativeTo(getParent());
}

From source file:CubaHSQLDBServer.java

private void addCopyPopup(final JTextArea source) {
    final JPopupMenu popup = new JPopupMenu();
    popup.add(new AbstractAction("Copy to clipboard") {
        @Override/*  w  ww.  ja  va  2 s. co  m*/
        public void actionPerformed(ActionEvent e) {
            StringSelection contents = new StringSelection(source.getText());
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(contents, contents);
        }
    });
    source.add(popup);
    source.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(source, e.getX(), e.getY());
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(source, e.getX(), e.getY());
            }
        }
    });
}