How to make a JPopupMenu in java with an item to copy text

163 views Asked by At

I want to know how to make a JPopupMenu that has an item to copy text. I have started with putting the label with a JPopupMenu.

What is the code for this item "Copy" in the JPopupMenu to copy the text?

1

There are 1 answers

0
cello On BEST ANSWER

The following should get you started: Add a JMenuItem to the popup with the copy command. In the actionPerformed-method, get the text you want to copy, and then pass it to the System Clipboard that you can get using the Toolkit class in Java:

popupMenu.add(new JMenuItem(new AbstractAction("Copy") {
    @Override
    public void actionPerformed(final ActionEvent e) {

        String text = field.getText(); // replace this to get the text you want to be copied
        StringSelection stsel = new StringSelection(text);
        Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();
        system.setContents(stsel, stsel);

    }
}));