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:com.igormaznitsa.ideamindmap.swing.PlainTextEditor.java

public PlainTextEditor(final Project project, final String text) {
    super(new BorderLayout());
    this.editor = new EmptyTextEditor(project);

    final JToolBar menu = new JToolBar();

    final JButton buttonImport = new JButton("Import", AllIcons.Buttons.IMPORT);
    final PlainTextEditor theInstance = this;

    buttonImport.addActionListener(new ActionListener() {
        @Override//from  w  ww . j  a v  a  2 s .  c  o  m
        public void actionPerformed(ActionEvent e) {
            final File home = new File(System.getProperty("user.home")); //NOI18N

            final File toOpen = IdeaUtils.chooseFile(theInstance, true,
                    BUNDLE.getString("PlainTextEditor.buttonLoadActionPerformed.title"), home,
                    TEXT_FILE_FILTER);

            if (toOpen != null) {
                try {
                    final String text = FileUtils.readFileToString(toOpen, "UTF-8"); //NOI18N
                    editor.setText(text);
                } catch (Exception ex) {
                    LOGGER.error("Error during text file loading", ex); //NOI18N
                    Messages.showErrorDialog(
                            BUNDLE.getString("PlainTextEditor.buttonLoadActionPerformed.msgError"), "Error");
                }
            }

        }
    });

    final JButton buttonExport = new JButton("Export", AllIcons.Buttons.EXPORT);
    buttonExport.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final File home = new File(System.getProperty("user.home")); //NOI18N
            final File toSave = IdeaUtils.chooseFile(theInstance, true,
                    BUNDLE.getString("PlainTextEditor.buttonSaveActionPerformed.saveTitle"), home,
                    TEXT_FILE_FILTER);
            if (toSave != null) {
                try {
                    final String text = getText();
                    FileUtils.writeStringToFile(toSave, text, "UTF-8"); //NOI18N
                } catch (Exception ex) {
                    LOGGER.error("Error during text file saving", ex); //NOI18N
                    Messages.showErrorDialog(
                            BUNDLE.getString("PlainTextEditor.buttonSaveActionPerformed.msgError"), "Error");
                }
            }
        }
    });

    final JButton buttonCopy = new JButton("Copy", AllIcons.Buttons.COPY);
    buttonCopy.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final StringSelection stringSelection = new StringSelection(editor.getSelectedText());
            final Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
            clpbrd.setContents(stringSelection, null);
        }
    });

    final JButton buttonPaste = new JButton("Paste", AllIcons.Buttons.PASTE);
    buttonPaste.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                final String clipboardText = (String) Toolkit.getDefaultToolkit().getSystemClipboard()
                        .getData(DataFlavor.stringFlavor);
                editor.replaceSelection(clipboardText);
            } catch (UnsupportedFlavorException ex) {
                // no text data in clipboard
            } catch (IOException ex) {
                LOGGER.error("Error during paste from clipboard", ex); //NOI18N
            }
        }
    });

    final JButton buttonClearAll = new JButton("Clear All", AllIcons.Buttons.CLEARALL);
    buttonClearAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            editor.clear();
        }
    });

    menu.add(buttonImport);
    menu.add(buttonExport);
    menu.add(buttonCopy);
    menu.add(buttonPaste);
    menu.add(buttonClearAll);

    this.add(menu, BorderLayout.NORTH);
    this.add(editor, BorderLayout.CENTER);

    // I made so strange trick to move the caret into the start of document, all other ways didn't work :(
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            editor.replaceSelection(text);
        }
    });
}

From source file:ca.wumbo.doommanager.client.controller.ConsoleController.java

/**
 * Takes whatever is in the text field and submits it.
 *//*from www. j  a  v a  2s .  c o  m*/
private void submitLineToConsole() {
    // Trim the string before using, also nulls shouldn't happen (but just in case).
    String text = textField.getText().trim().replace('\0', '?');

    // Ignore empty lines.
    if (text.isEmpty())
        return;

    // Remember what we submitted, most recent goes first.
    commandBuffer.add(text);

    // Reset due to submission of text.
    commandBufferIndex = commandBuffer.size();

    // Handle commands.
    switch (text.toLowerCase()) {
    case "clear":
        textArea.clear();
        break;

    case "connect": // Note: Debugging only.
        textArea.appendText("Starting connection to local host..." + System.lineSeparator());
        Optional<SelectionKey> key = clientSelector.openTCPConnection(
                new InetSocketAddress("localhost", Server.DEFAULT_LISTEN_PORT), new NetworkReceiver() {
                    @Override
                    public void signalConnectionTerminated() {
                        System.out.println("Test connection killed.");
                    }

                    @Override
                    public void receiveData(byte[] data) {
                        System.out.println("Got data: " + data.length + " = " + Arrays.toString(data));
                    }
                });
        if (key.isPresent()) {
            SelectionKey k = key.get();
            Platform.runLater(() -> {
                try {
                    Thread.sleep(2000);
                    clientSelector.writeData(k, new byte[] { 1, 2 });
                    System.out.println("Go forth...");
                } catch (Exception e) {
                    System.err.println("UGH");
                    e.printStackTrace();
                }
            });
        }
        textArea.appendText("Connection made = " + key.isPresent() + System.lineSeparator());
        break;

    case "copy":
        try {
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            StringSelection stringSelection = new StringSelection(textArea.getText());
            clipboard.setContents(stringSelection, stringSelection);
            textArea.appendText("Copied to clipboard." + System.lineSeparator());
        } catch (Exception e) {
            textArea.appendText("Error: Unable to get system clipboard." + System.lineSeparator());
        }
        break;

    case "exit":
        coreController.exit();
        break;

    case "getconnections":
        int numKeys = clientSelector.getNumConnections();
        textArea.appendText("There " + (numKeys != 1 ? "are " : "is ") + numKeys + " key"
                + (numKeys != 1 ? "s." : ".") + System.lineSeparator());
        break;

    case "help":
        textArea.appendText("Commands:" + System.lineSeparator());
        textArea.appendText("    clear - Clears the console" + System.lineSeparator());
        textArea.appendText("    copy - Copies all the content to your clipboard" + System.lineSeparator());
        textArea.appendText("    exit - Exits the program" + System.lineSeparator());
        textArea.appendText("    getconnections - Lists the connections available" + System.lineSeparator());
        textArea.appendText("    help - Shows this help" + System.lineSeparator());
        textArea.appendText("    history - Prints command history for " + MAX_COMMANDS_REMEMBERED + " entries"
                + System.lineSeparator());
        textArea.appendText("    memory - Get current memory statistics" + System.lineSeparator());
        textArea.appendText("    version - Gets the version information" + System.lineSeparator());
        break;

    case "history":
        if (commandBuffer.size() <= 1) {
            textArea.appendText("No history to display" + System.lineSeparator());
            break;
        }
        textArea.appendText("History:" + System.lineSeparator());
        for (int i = 0; i < commandBuffer.size() - 1; i++)
            textArea.appendText("    " + commandBuffer.get(i) + System.lineSeparator()); // Print everything but the last command (which was this).
        break;

    case "memory":
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(2);
        long totalMem = Runtime.getRuntime().totalMemory();
        long usedMem = totalMem - Runtime.getRuntime().freeMemory();
        long maxMem = Runtime.getRuntime().maxMemory();
        double megabyte = 1024.0 * 1024.0;
        textArea.appendText("Memory statistics:" + System.lineSeparator());
        textArea.appendText(
                "    Memory used: " + nf.format(Math.abs(((double) usedMem / (double) maxMem)) * 100.0) + "%"
                        + System.lineSeparator());
        textArea.appendText(
                "    " + nf.format(usedMem / megabyte) + " mb (used memory)" + System.lineSeparator());
        textArea.appendText(
                "    " + nf.format(maxMem / megabyte) + " mb (max memory)" + System.lineSeparator());
        break;

    // DEBUG
    case "startserver":
        if (Start.getParsedRuntimeArgs().isClientServer()) {
            if (!serverManager.isInitialized()) {
                try {
                    textArea.appendText("Starting server on port " + Server.DEFAULT_LISTEN_PORT + "."
                            + System.lineSeparator());
                    serverManager.initialize();
                } catch (Exception e) {
                    textArea.appendText("Unable to initialize server." + System.lineSeparator());
                    textArea.appendText("    " + e.getMessage() + System.lineSeparator());
                }
            }

            if (serverManager.isInitialized()) {
                if (!serverManager.isRunning()) {
                    textArea.appendText("Running server on port " + Server.DEFAULT_LISTEN_PORT + "."
                            + System.lineSeparator());
                    try {
                        new Thread(serverManager, "ClientConsoleServer").start();
                        textArea.appendText("Successfully set up server." + System.lineSeparator());
                    } catch (Exception e) {
                        textArea.appendText("Error setting up server:" + System.lineSeparator());
                        textArea.appendText("    " + e.getMessage() + System.lineSeparator());
                    }
                } else {
                    textArea.appendText("Server is already running." + System.lineSeparator());
                }
            } else {
                textArea.appendText("Server not initialized, cannot run." + System.lineSeparator());
            }
        }
        break;

    // DEBUG
    case "stopserver":
        if (Start.getParsedRuntimeArgs().isClientServer()) {
            if (serverManager.isInitialized() && serverManager.isRunning()) {
                serverManager.requestServerTermination();
                textArea.appendText("Requested server termination." + System.lineSeparator());
            } else {
                textArea.appendText(
                        "Cannot stop server, it has not been initialized or started." + System.lineSeparator());
            }
        }
        break;

    case "version":
        textArea.appendText(applicationTitle + " version: " + applicationVersion + System.lineSeparator());
        break;

    default:
        textArea.appendText("Unknown command: " + text + System.lineSeparator());
        textArea.appendText("Type 'help' for commands" + System.lineSeparator());
        break;
    }

    textField.clear();
}

From source file:com.yosanai.java.aws.console.panel.InstancesPanel.java

protected void setToClipBoard(String data) {
    StringSelection clipData = new StringSelection(data);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(clipData, clipData);
}

From source file:org.pentaho.ui.xul.swing.tags.SwingWindow.java

public void copy(String content) throws XulException {
    StringSelection data = new StringSelection(content);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(data, data);// w ww  .java  2  s.  c  om
}

From source file:de.rkl.tools.tzconv.TimezoneConverter.java

private Node createCopyToClipboard(final TextInputControl mainArea) {
    final Button copyToClipboard = new Button("Copy to Clipboard");
    copyToClipboard.setOnAction(event -> {
        final StringSelection stringSelection = new StringSelection(mainArea.textProperty().getValue());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, stringSelection);
    });//  ww  w .  j a v a 2  s.  co m
    final HBox copyToClipboardBox = new HBox(copyToClipboard);
    copyToClipboardBox.alignmentProperty().setValue(Pos.CENTER);
    return copyToClipboardBox;
}

From source file:UploadUtils.PomfUpload.java

/**
 * Copy image link to user's clipboard.//from  w  ww  . j a  va  2 s .  c  o  m
 * This method could be called in onImageLink(String link) to copy the link to the user's clipboard.
 * @param link the string to copy to the clipboard
 */
public static void copyToClipBoard(String link) {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Clipboard clipboard = toolkit.getSystemClipboard();
    StringSelection selection = new StringSelection(link);
    clipboard.setContents(selection, null);
}

From source file:ja.lingo.application.gui.main.describer.DescriberGui.java

public void copySelected() {
    //articlePanel.getEditorPane().copy(); // TODO JEditorPane.copy() doesn't work. Why? Tested with 1.5.0_05.
    StringSelection selection = new StringSelection(articlePanel.getEditorPane().getSelectedText());
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
}

From source file:org.orbisgis.sif.components.fstree.TreeNodeFolder.java

/**
 * Copy the folder path to the ClipBoard
 *//*from  w w w.java2 s.c o  m*/
public void onCopyPath() {
    StringSelection pathString = new StringSelection(getFilePath().getAbsolutePath());
    try {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(pathString, pathString);
        LOGGER.info(I18N.tr("The path {0} has been copied to the clipboard", getFilePath().getAbsolutePath()));
    } catch (Throwable ex) {
        LOGGER.error(I18N.tr("Could not copy the folder path to the clipboard"), ex);
    }
}

From source file:org.rdv.ui.DataPanelContainer.java

public void dragGestureRecognized(DragGestureEvent e) {
    e.startDrag(DragSource.DefaultMoveDrop, new StringSelection(""), this);
}

From source file:edu.uchc.octane.OctaneWindowControl.java

/**
 * Copy selected trajectories to system clipboard
 *///from w  ww.j a va  2 s .c o  m
protected void copySelectedTrajectories() {

    StringBuilder buf = new StringBuilder();
    int[] selected = frame_.getTrajsTable().getSelectedTrajectories();
    Trajectory traj;

    for (int i = 0; i < selected.length; i++) {

        traj = dataset_.getTrajectoryByIndex(selected[i]);

        for (int j = 0; j < traj.size(); j++) {

            buf.append(String.format("%10.4f, %10.4f, %10d, %5d%n", traj.get(j).x, traj.get(j).y,
                    traj.get(j).frame, i));

        }
    }

    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection contents = new StringSelection(buf.toString());
    clipboard.setContents(contents, this);
}