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:de.tor.tribes.ui.views.DSWorkbenchSelectionFrame.java

private void copyBBToExternalClipboardEvent() {
    try {/*from  w  w  w  .j  a  v  a 2 s. c  om*/
        List<Village> selection = getSelectedElements();
        if (selection.isEmpty()) {
            showInfo("Keine Elemente ausgewhlt");
            return;
        }
        boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
                "Nein", "Ja") == JOptionPane.YES_OPTION);

        StringBuilder buffer = new StringBuilder();
        if (extended) {
            buffer.append("[u][size=12]Dorfliste[/size][/u]\n\n");
        } else {
            buffer.append("[u]Dorfliste[/u]\n\n");
        }
        buffer.append(new VillageListFormatter().formatElements(selection, extended));

        if (extended) {
            buffer.append("\n[size=8]Erstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "[/size]\n");
        } else {
            buffer.append("\nErstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "\n");
        }

        String b = buffer.toString();
        StringTokenizer t = new StringTokenizer(b, "[");
        int cnt = t.countTokens();
        if (cnt > 1000) {
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Die ausgewhlten Drfer bentigen mehr als 1000 BB-Codes\n"
                            + "und knnen daher im Spiel (Forum/IGM/Notizen) nicht auf einmal dargestellt werden.\nTrotzdem exportieren?",
                    "Zu viele BB-Codes", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                return;
            }
        }

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b), null);
        showSuccess("Daten in Zwischenablage kopiert");
    } catch (Exception e) {
        logger.error("Failed to copy data to clipboard", e);
        showError("Fehler beim Kopieren in die Zwischenablage");
    }
}

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

private void transferSelectedTagsToJS() {
    List<Tag> selection = getSelectedTags();
    if (selection.isEmpty()) {
        showInfo("Keine Gruppe ausgewhlt");
        return;/*  ww  w  .  j a va2 s  .  com*/
    }

    List<Integer> villageIds = new LinkedList<>();
    for (Tag t : selection) {
        for (Integer id : t.getVillageIDs()) {
            if (!villageIds.contains(id)) {
                villageIds.add(id);
            }
        }
    }

    if (villageIds.isEmpty()) {
        showInfo("Die gewhlten Gruppen enthalten keine Drfer");
    }
    StringBuilder data = new StringBuilder();

    try {
        for (Integer id : villageIds) {
            data.append(id).append(";");
        }
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(data.toString()),
                null);
        showSuccess(
                "<html>D&ouml;rfer erfolgreich in die Zwischenablage kopiert.<br/>F&uuml;ge sie nun in der Gruppen&uuml;bersicht in das entsprechende Feld unterhalb einer leeren Gruppe ein und weise sie dadurch dieser Gruppe zu.</html>");
    } catch (HeadlessException he) {
        logger.error("Failed to copy data to clipboard", he);
        showError("Fehler beim Kopieren in die Zwischenablage");
    }
}

From source file:org.isatools.isacreator.spreadsheet.SpreadsheetFunctions.java

/**
 * Performs a clipboard function of cut/copy
 *
 * @param isCut true for cut, false for copy
 * @param toUse - the SpreadsheetCellRange representing the values to be pasted into the spreadsheet
 *//*w w w .java 2s . c o m*/

public void doCopy(boolean isCut, SpreadsheetCellRange toUse) {
    CellEditor editor = spreadsheet.getTable().getCellEditor();
    if (editor != null) {
        editor.cancelCellEditing();
    }
    boolean modifiedCellRange = false;
    if (spreadsheet.getTable().getSelectedRowCount() != 0 || toUse != null) {
        if (toUse == null) {

            toUse = new SpreadsheetCellRange(spreadsheet.getTable().getSelectedRows(),
                    Utils.convertSelectedColumnsToModelIndices(spreadsheet.getTable(),
                            spreadsheet.getTable().getSelectedColumns()));
            modifiedCellRange = true;
        }

        if (isCut && modifiedCellRange) {
            spreadsheet.spreadsheetHistory.add(toUse);
        }

        String str = spreadsheet.spreadsheetModel.extendedToString(toUse, '\t');
        StringSelection stsel = new StringSelection(str);
        spreadsheet.system.setContents(stsel, stsel);

        if (isCut) {
            spreadsheet.spreadsheetModel.clearRange(toUse);
        }

        spreadsheet.notifyObservers(SpreadsheetEvent.COPY);
    } else {
        System.out.println("no rows are selected so no copying has taken place.");
    }

}

From source file:com.mirth.connect.connectors.ws.WebServiceSender.java

private void setAttachments(List<List<String>> attachments) {

    List<String> attachmentIds = attachments.get(0);
    List<String> attachmentContents = attachments.get(1);
    List<String> attachmentTypes = attachments.get(2);

    Object[][] tableData = new Object[attachmentIds.size()][3];

    attachmentsTable = new MirthTable();

    for (int i = 0; i < attachmentIds.size(); i++) {
        tableData[i][ID_COLUMN_NUMBER] = attachmentIds.get(i);
        tableData[i][CONTENT_COLUMN_NUMBER] = attachmentContents.get(i);
        tableData[i][MIME_TYPE_COLUMN_NUMBER] = attachmentTypes.get(i);
    }//from ww  w.  ja  va 2 s  .co  m

    attachmentsTable.setModel(new javax.swing.table.DefaultTableModel(tableData,
            new String[] { ID_COLUMN_NAME, CONTENT_COLUMN_NAME, MIME_TYPE_COLUMN_NAME }) {

        boolean[] canEdit = new boolean[] { true, true, true };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }
    });

    attachmentsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent evt) {
            if (attachmentsTable.getSelectedModelIndex() != -1) {
                deleteButton.setEnabled(true);
            } else {
                deleteButton.setEnabled(false);
            }
        }
    });

    class AttachmentsTableCellEditor extends TextFieldCellEditor {

        boolean checkUnique;

        public AttachmentsTableCellEditor(boolean checkUnique) {
            super();
            this.checkUnique = checkUnique;
        }

        public boolean checkUnique(String value) {
            boolean exists = false;

            for (int i = 0; i < attachmentsTable.getModel().getRowCount(); i++) {
                if (((String) attachmentsTable.getModel().getValueAt(i, ID_COLUMN_NUMBER))
                        .equalsIgnoreCase(value)) {
                    exists = true;
                }
            }

            return exists;
        }

        @Override
        public boolean isCellEditable(EventObject evt) {
            boolean editable = super.isCellEditable(evt);

            if (editable) {
                deleteButton.setEnabled(false);
            }

            return editable;
        }

        @Override
        protected boolean valueChanged(String value) {
            deleteButton.setEnabled(true);

            if (checkUnique && (value.length() == 0 || checkUnique(value))) {
                return false;
            }

            parent.setSaveEnabled(true);
            return true;
        }
    }

    attachmentsTable.getColumnModel().getColumn(attachmentsTable.getColumnModelIndex(ID_COLUMN_NAME))
            .setCellEditor(new AttachmentsTableCellEditor(true));
    attachmentsTable.getColumnModel().getColumn(attachmentsTable.getColumnModelIndex(CONTENT_COLUMN_NAME))
            .setCellEditor(new AttachmentsTableCellEditor(false));
    attachmentsTable.getColumnModel().getColumn(attachmentsTable.getColumnModelIndex(MIME_TYPE_COLUMN_NAME))
            .setCellEditor(new AttachmentsTableCellEditor(false));
    attachmentsTable.setCustomEditorControls(true);

    attachmentsTable.setSelectionMode(0);
    attachmentsTable.setRowSelectionAllowed(true);
    attachmentsTable.setRowHeight(UIConstants.ROW_HEIGHT);
    attachmentsTable.setDragEnabled(true);

    attachmentsTable.setTransferHandler(new TransferHandler() {

        protected Transferable createTransferable(JComponent c) {
            try {
                MirthTable table = ((MirthTable) (c));

                if (table == null) {
                    return null;
                }

                int currRow = table.convertRowIndexToModel(table.getSelectedRow());

                String text = "";
                if (currRow >= 0 && currRow < table.getModel().getRowCount()) {
                    text = (String) table.getModel().getValueAt(currRow, ID_COLUMN_NUMBER);
                }

                text = "<inc:Include href=\"cid:" + text
                        + "\" xmlns:inc=\"http://www.w3.org/2004/08/xop/include\"/>";

                return new StringSelection(text);
            } catch (ClassCastException cce) {
                return null;
            }
        }

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        public boolean canImport(JComponent c, DataFlavor[] df) {
            return false;
        }
    });

    attachmentsTable.setOpaque(true);
    attachmentsTable.setSortable(true);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        attachmentsTable.setHighlighters(highlighter);
    }

    attachmentsPane.setViewportView(attachmentsTable);
    deleteButton.setEnabled(false);
}

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

private void copySelectionToClipboardAsBBCode() {
    HashMap<Tribe, SOSRequest> selectedRequests = new HashMap<>();
    List<DefenseInformation> selection = getSelectedRows();
    if (selection.isEmpty()) {
        showInfo("Keine SOS Anfragen eingelesen");
        return;/*from ww w .  ja  v a 2  s .com*/
    }

    for (DefenseInformation info : selection) {
        Tribe defender = info.getTarget().getTribe();
        SOSRequest request = selectedRequests.get(defender);
        if (request == null) {
            request = new SOSRequest(defender);
            selectedRequests.put(defender, request);
        }
        TargetInformation targetInfo = request.addTarget(info.getTarget());
        targetInfo.merge(info.getTargetInformation());
    }

    try {
        boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
                "Nein", "Ja") == JOptionPane.YES_OPTION);

        StringBuilder buffer = new StringBuilder();
        if (extended) {
            buffer.append("[u][size=12]SOS Anfragen[/size][/u]\n\n");
        } else {
            buffer.append("[u]SOS Anfragen[/u]\n\n");
        }

        List<SOSRequest> requests = new LinkedList<>();
        CollectionUtils.addAll(requests, selectedRequests.values());
        buffer.append(new SosListFormatter().formatElements(requests, extended));

        if (extended) {
            buffer.append("\n[size=8]Erstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "[/size]\n");
        } else {
            buffer.append("\nErstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "\n");
        }

        String b = buffer.toString();
        StringTokenizer t = new StringTokenizer(b, "[");
        int cnt = t.countTokens();
        if (cnt > 1000) {
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Die momentan vorhandenen Anfragen bentigen mehr als 1000 BB-Codes\n"
                            + "und knnen daher im Spiel (Forum/IGM/Notizen) nicht auf einmal dargestellt werden.\nTrotzdem exportieren?",
                    "Zu viele BB-Codes", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                return;
            }
        }

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b), null);
        showSuccess("Daten in Zwischenablage kopiert");
    } catch (Exception e) {
        logger.error("Failed to copy data to clipboard", e);
        showError("Fehler beim Kopieren in die Zwischenablage");
    }

}

From source file:ca.uhn.hl7v2.testpanel.ui.editor.Hl7V2MessageEditorPanel.java

private void initLocal() {

    myDocumentListener = new DocumentListener() {

        public void changedUpdate(DocumentEvent theE) {
            ourLog.info("Document change: " + theE);
            handleChange(theE);/*from  ww w  .  ja  v  a  2 s  .  c  o m*/
        }

        private void handleChange(DocumentEvent theE) {
            myDontRespondToSourceMessageChanges = true;
            try {
                long start = System.currentTimeMillis();

                String newSource = myMessageEditor.getText();
                int changeStart = theE.getOffset();
                int changeEnd = changeStart + theE.getLength();
                myMessage.updateSourceMessage(newSource, changeStart, changeEnd);

                ourLog.info("Handled document update in {} ms", System.currentTimeMillis() - start);
            } finally {
                myDontRespondToSourceMessageChanges = false;
            }
        }

        public void insertUpdate(DocumentEvent theE) {
            ourLog.info("Document insert: " + theE);
            handleChange(theE);
        }

        public void removeUpdate(DocumentEvent theE) {
            ourLog.info("Document removed: " + theE);
            handleChange(theE);
        }
    };
    myMessageEditor.getDocument().addDocumentListener(myDocumentListener);

    myMessageEditor.addCaretListener(new CaretListener() {

        public void caretUpdate(final CaretEvent theE) {
            removeMostHighlights();
            if (!myDisableCaretUpdateHandling) {
                myController.invokeInBackground(new Runnable() {
                    @Override
                    public void run() {
                        myMessage.setHighlitedPathBasedOnRange(new Range(theE.getDot(), theE.getMark()));
                        myTreePanel.repaint();
                    }
                });
            }
        }
    });

    updateOutboundConnectionsBox();
    myOutboundConnectionsListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            updateOutboundConnectionsBox();
        }
    };
    myController.getOutboundConnectionList().addPropertyChangeListener(OutboundConnectionList.PROP_LIST,
            myOutboundConnectionsListener);

    myOutboundInterfaceCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent theE) {
            if (!myOutboundInterfaceComboModelIsUpdating) {
                updateSendButton();
            }
        }

    });

    JMenuItem copyMenuItem = new JMenuItem("Copy to Clipboard");
    copyMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent theE) {
            String selection = myTerserPathTextField.getText();
            StringSelection data = new StringSelection(selection);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(data, data);
        }
    });
    myTerserPathPopupMenu.add(copyMenuItem);

    myProfilesListener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent theEvt) {
            myProfileComboboxModel.update();
            registerProfileNamesListeners();
        }
    };
    myController.getProfileFileList().addPropertyChangeListener(ProfileFileList.PROP_FILES, myProfilesListener);
    registerProfileNamesListeners();

    myProfilesNamesListener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent theEvt) {
            myProfileComboboxModel.update();
        }
    };

}

From source file:acmi.l2.clientmod.l2smr.Controller.java

@FXML
private void copyNameToClipboard() {
    Actor selected = this.table.getSelectionModel().getSelectedItem();
    if (selected == null)
        return;/*from   ww w. ja va2  s .c om*/

    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(selected.getStaticMesh()),
            null);
}

From source file:org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils.java

public static void uploadFileWithJavaRobot(String FilePath, String FileName) throws Exception {
    StringSelection sel = new StringSelection(FilePath + FileName);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null);
    Thread.sleep(1000);//from  w  ww .j  a v  a  2s  . c o  m
    Robot robot = new Robot();
    robot.delay(1000);

    // Release Enter
    robot.keyRelease(KeyEvent.VK_ENTER);

    // Press CTRL+V
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);

    // Release CTRL+V
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_V);
    Thread.sleep(1000);

    // Press Enter
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    Thread.sleep(3000);
}

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

private void copyToClipboard(String s) {
    StringSelection stringSelection = new StringSelection(s);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, stringSelection);
}

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

/**
 * This method takes in a JTextField object and then copies the text of that
 * text field to the system clipboard./*from  w  w  w .j  a  v  a 2 s  .c  om*/
 * 
 * @param textField
 */
public void copyTextField(JTextField textField) {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection selected = new StringSelection(textField.getText());
    clipboard.setContents(selected, selected);
}