Example usage for java.awt.datatransfer Clipboard setContents

List of usage examples for java.awt.datatransfer Clipboard setContents

Introduction

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

Prototype

public synchronized void setContents(Transferable contents, ClipboardOwner owner) 

Source Link

Document

Sets the current contents of the clipboard to the specified transferable object and registers the specified clipboard owner as the owner of the new contents.

Usage

From source file:org.zanata.page.webtrans.EditorPage.java

/**
 * Simulate a paste from the user's clipboard into the indicated row
 *
 * @param rowIndex//from  w  ww. j  av a2  s . c o  m
 *            row to enter text
 * @param text
 *            text to be entered
 * @return new EditorPage
 */
public EditorPage pasteIntoRowAtIndex(final long rowIndex, final String text) {
    log.info("Paste at {} the text {}", rowIndex, text);
    WebElement we = readyElement(By.id(String.format(TARGET_ID_FMT, rowIndex, Plurals.SourceSingular.index())));
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(new StringSelection(text), null);
    we.click();
    we.sendKeys(Keys.LEFT_CONTROL + "v");
    return new EditorPage(getDriver());
}

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

/**
 * Copy the folder path to the ClipBoard
 *//*from  w  ww .  ja  va  2s.  com*/
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:de.mycrobase.jcloudapp.Main.java

private void setClipboard(String s) {
    Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
    cb.setContents(new StringSelection(s), null);

    // designated use, alert user when he could finally use the URL
    Toolkit.getDefaultToolkit().beep();
}

From source file:com.jk.framework.util.FakeRunnable.java

/**
 * Copy to clipboard./*from w ww.ja  va2s  .c  o  m*/
 *
 * @param aString
 *            String
 */
public static void copyToClipboard(final String aString) {
    final StringSelection stringSelection = new StringSelection(aString);
    final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, stringSelection);
}

From source file:biz.wolschon.finance.jgnucash.accountProperties.AccountProperties.java

private JPopupMenu createAccountIDPopupMenu() {
    final JPopupMenu accountIDPopupMenu = new JPopupMenu();
    JMenuItem copyAccountIDMenuItem = new JMenuItem("copy");
    copyAccountIDMenuItem.addActionListener(new ActionListener() {

        @Override/*  w w  w. j  a  v  a2s . c  o m*/
        public void actionPerformed(final ActionEvent arg0) {
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(new StringSelection(myAccount.getId()), AccountProperties.this);
        }
    });
    accountIDPopupMenu.add(copyAccountIDMenuItem);
    return accountIDPopupMenu;
}

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

/**
 * Takes whatever is in the text field and submits it.
 *//*www  .  j  ava  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:de.codesourcery.eve.skills.ui.components.impl.planning.CostStatementComponent.java

protected void putOnClipboard() {

    // create text
    final SpreadSheetTableModel model = (SpreadSheetTableModel) this.table.getModel();

    int maxColumnCount = 1;

    final Map<Integer, Integer> maxColumnWidth = new HashMap<Integer, Integer>();

    for (TableRow r : model.getRows()) {
        if (r.getCellCount() > maxColumnCount) {
            maxColumnCount = r.getCellCount();
        }//ww  w.  j a v  a2s  .c  o  m

        for (int i = 0; i < r.getCellCount(); i++) {

            Integer maxWidth = maxColumnWidth.get(i);
            if (maxWidth == null) {
                maxWidth = new Integer(0);
                maxColumnWidth.put(i, maxWidth);
            }
            final ITableCell cell = r.getCell(i);
            if (cell.getValue() != null) {
                final int len = toString(cell).length();

                if (len > maxWidth.intValue()) {
                    maxWidth = new Integer(len);
                    maxColumnWidth.put(i, maxWidth);
                }
            }
        }
    }

    final StringBuffer text = new StringBuffer();

    for (TableRow r : model.getRows()) {
        for (int i = 0; i < r.getCellCount(); i++) {
            final int width = maxColumnWidth.get(i);
            final ITableCell cell = r.getCell(i);
            if (i == 0) {
                text.append(StringUtils.rightPad(toString(cell), width)).append(" | ");
            } else {
                text.append(StringUtils.leftPad(toString(cell), width)).append(" | ");
            }
        }
        text.append("\n");
    }

    // put on clipboard
    final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    clipboard.setContents(new PlainTextTransferable(text.toString()), null);
}

From source file:net.ytbolg.mcxa.ForgeCheck.java

@Override
public void run() {
    System.out.println(Lang.getLang("Forge_StartDown") + "http://bmclapi.bangbang93.com/forge/getforge" + "/"
            + version + "/" + forgeversion);
    downloadFile("http://bmclapi.bangbang93.com/forge/getforge" + "/" + version + "/" + forgeversion,
            GameInfo.Rundir + tpf + "forgetmp.jar");
    //   downloadFile("http://bmclapi.bangbang93.com/versions/" + version + "/" + version + ".json", GameInfo.GameDir + tpf + "versions" + tpf + version + tpf + version + ".json");
    JOptionPane.showMessageDialog(null, Lang.getLang("Forge_DownSucc"));
    j.setValue(0);/*www.j  a v  a  2  s  .  c  om*/
    l.setText("");
    JOptionPane.showMessageDialog(null, Lang.getLang("Forge_SetupForge"));
    Clipboard clipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
    //  String vc = refContent.trim();  
    //  StringSelection ss = new StringSelection(vc);  

    StringSelection selection = new StringSelection(GameInfo.GameDir);//?step1:?Transferable???StringSelectionTransferable?
    clipBoard.setContents(selection, null);//?step2.?Owner
    try {
        Runtime.getRuntime().exec("java -jar " + GameInfo.Rundir + tpf + "forgetmp.jar");
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    } catch (IOException ex) {
        Logger.getLogger(DownloadForge.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:view.App.java

private void initGUI() {
    try {/*w  w  w  . j a  va2s.  c o m*/
        {
            jPanel1 = new JPanel();
            BorderLayout jPanel1Layout = new BorderLayout();
            jPanel1.setLayout(jPanel1Layout);
            getContentPane().add(jPanel1, BorderLayout.CENTER);
            jPanel1.setPreferredSize(new java.awt.Dimension(901, 398));
            {
                jPanel2 = new JPanel();
                BoxLayout jPanel2Layout = new BoxLayout(jPanel2, javax.swing.BoxLayout.Y_AXIS);
                jPanel2.setLayout(jPanel2Layout);
                jPanel1.add(jPanel2, BorderLayout.WEST);
                jPanel2.setPreferredSize(new java.awt.Dimension(292, 446));
                {
                    jPanel5 = new JPanel();
                    jPanel2.add(jPanel5);
                    jPanel5.setPreferredSize(new java.awt.Dimension(292, 109));
                    {
                        {
                            jTextArea1 = new JTextArea();
                            jTextArea1.setWrapStyleWord(true);
                            jTextArea1.setLineWrap(true);
                            DefaultCaret caret = (DefaultCaret) jTextArea1.getCaret();
                            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

                            jTextArea1.addFocusListener(new FocusAdapter() {
                                public void focusGained(FocusEvent evt) {

                                    if (jTable1.getModel().getRowCount() == 0 && !jButton1.isEnabled()) {
                                        jButton1.setEnabled(true);
                                        jTextArea1.setText("");
                                    }

                                }
                            });
                            JScrollPane sp = new JScrollPane();
                            sp.setPreferredSize(new java.awt.Dimension(281, 97));
                            sp.setViewportView(jTextArea1);

                            jPanel5.add(sp, BorderLayout.CENTER);
                        }
                    }

                }
                {
                    jPanel4 = new JPanel();
                    jPanel2.add(jPanel4);
                    FlowLayout jPanel4Layout = new FlowLayout();
                    jPanel4Layout.setAlignment(FlowLayout.RIGHT);
                    jPanel4.setPreferredSize(new java.awt.Dimension(292, 45));
                    jPanel4.setSize(102, 51);
                    jPanel4.setLayout(jPanel4Layout);
                    {
                        jButton1 = new JButton();
                        jPanel4.add(jButton1);
                        jButton1.setText("Get Quotes");
                        jButton1.setSize(100, 50);
                        jButton1.setPreferredSize(new java.awt.Dimension(100, 26));
                        jButton1.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                //   
                                String tickerStr = jTextArea1.getText();
                                if (tickerStr.equals("") || tickerStr.equals(null)
                                        || tickerStr.equals(" ")) {
                                    jTextArea1.setText(" ");
                                    return;
                                }
                                StringTokenizer tokenizer = new StringTokenizer(tickerStr, " ");
                                String[] tickers = new String[tokenizer.countTokens()];
                                int i = 0;
                                while (tokenizer.hasMoreTokens()) {
                                    tickers[i] = tokenizer.nextToken();
                                    i++;
                                }
                                try {
                                    Controller.getQuotes(tickers);
                                } catch (CloneNotSupportedException e) {
                                    JOptionPane.showMessageDialog(jPanel1, "   ");
                                }
                                jButton1.setEnabled(false);
                            }
                        });
                    }
                }
                {
                    jPanel6 = new JPanel();
                    BorderLayout jPanel6Layout = new BorderLayout();
                    jPanel6.setLayout(jPanel6Layout);
                    jPanel2.add(jPanel6);
                    {
                        jScrollPane1 = new JScrollPane();
                        jPanel6.add(jScrollPane1, BorderLayout.CENTER);
                        jScrollPane1.setPreferredSize(new java.awt.Dimension(292, 341));
                        {
                            TableModel jTable1Model = new DefaultTableModel(null,
                                    new String[] { "", "MA Value", "", "MA Value" });
                            jTable1 = new JTable();

                            jScrollPane1.setViewportView(jTable1);
                            jTable1.setModel(jTable1Model);
                            jTable1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

                        }
                    }
                }
            }
            {
                jPanel3 = new JPanel();
                BorderLayout jPanel3Layout = new BorderLayout();
                jPanel3.setLayout(jPanel3Layout);
                jPanel1.add(jPanel3, BorderLayout.CENTER);
                {
                    //                  chart = ChartFactory.createLineChart(" ", "dates", "correlation ratio", null, 
                    //                        PlotOrientation.VERTICAL, true, true, false);
                    //                  ChartPanel chartPanel = new ChartPanel(chart);
                    //                  chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) );
                    //                  jPanel3.add(chartPanel);
                }
                {

                }
            }
        }
        this.setSize(966, 531);
        {
            jMenuBar1 = new JMenuBar();
            setJMenuBar(jMenuBar1);
            {
                jMenu3 = new JMenu();
                jMenuBar1.add(jMenu3);
                jMenu3.setText("File");
                {
                    //                  newFileMenuItem = new JMenuItem();
                    //                  jMenu3.add(newFileMenuItem);
                    //                  newFileMenuItem.setText("New");
                    //                  newFileMenuItem.addActionListener(new ActionListener() {
                    //                     public void actionPerformed(ActionEvent evt) {
                    ////                        jTextArea1.setText("");
                    ////                        DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
                    ////                        model.setRowCount(0);
                    ////                        Controller.clearPortfolio();
                    //                     }
                    //                  });
                }
                {
                    jSeparator2 = new JSeparator();
                    jMenu3.add(jSeparator2);
                }
                {
                    exitMenuItem = new JMenuItem();
                    jMenu3.add(exitMenuItem);
                    exitMenuItem.setText("Exit");
                    exitMenuItem.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            int action = JOptionPane.showConfirmDialog(jPanel1,
                                    "     ?", "Confirm Exit",
                                    JOptionPane.OK_CANCEL_OPTION);

                            if (action == JOptionPane.OK_OPTION)
                                System.exit(0);

                        }
                    });
                }
            }
            {
                jMenu4 = new JMenu();
                jMenuBar1.add(jMenu4);
                jMenu4.setText("Edit");
                {
                    cutMenuItem = new JMenuItem();
                    jMenu4.add(cutMenuItem);
                    cutMenuItem.setText("Cut");
                    cutMenuItem.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            String txt = jTextArea1.getText();
                            StringSelection selection = new StringSelection(txt);
                            Clipboard clp = Toolkit.getDefaultToolkit().getSystemClipboard();
                            clp.setContents(selection, null);
                            jTextArea1.setText("");

                        }
                    });
                }
                {
                    copyMenuItem = new JMenuItem();
                    jMenu4.add(copyMenuItem);
                    copyMenuItem.setText("Copy");
                    copyMenuItem.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent arg0) {
                            String txt = jTextArea1.getText();
                            StringSelection selection = new StringSelection(txt);
                            Clipboard clp = Toolkit.getDefaultToolkit().getSystemClipboard();
                            clp.setContents(selection, null);

                        }
                    });
                }
                {
                    pasteMenuItem = new JMenuItem();
                    jMenu4.add(pasteMenuItem);
                    pasteMenuItem.setText("Paste");
                    pasteMenuItem.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            Clipboard clp = Toolkit.getDefaultToolkit().getSystemClipboard();
                            try {
                                String data = (String) clp.getData(DataFlavor.stringFlavor);
                                jTextArea1.setText(data);
                            } catch (UnsupportedFlavorException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            } catch (IOException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                        }
                    });
                }
            }
            {
                jMenu5 = new JMenu();
                jMenuBar1.add(jMenu5);
                jMenu5.setText("Help");
                {
                    helpMenuItem = new JMenuItem();
                    jMenu5.add(helpMenuItem);
                    helpMenuItem.setText("About");
                    helpMenuItem.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent arg0) {
                            JOptionPane.showMessageDialog(jPanel1,
                                    "    .    r.zhumagulov@gmail.com",
                                    "About", JOptionPane.PLAIN_MESSAGE);

                        }
                    });
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:biomine.bmvis2.Vis.java

public void setClipboard(String str) {
    assert str != null : "Null str";
    AppletContext appletContext = null;
    try {/*from w w w .  j av a2  s  . c  o  m*/
        appletContext = getAppletContext();
    } catch (Exception e) {
    }

    Clipboard clipboard;
    StringSelection data = new StringSelection(str);

    try {
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        if (clipboard != null) {
            clipboard.setContents(data, null);
        }
    } catch (java.security.AccessControlException e) {
        if (appletContext != null) {
            try {
                str = str.replace('\'', '"');
                appletContext
                        .showDocument(new URL("javascript:copyToClipboard(encodeURIComponent('" + str + "'))"));
            } catch (Exception e2) {
                JOptionPane.showMessageDialog(null, e2.getMessage(), "Copying to clipboard failed",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Copying to clipboard failed",
                JOptionPane.ERROR_MESSAGE);
    }
}