0

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
The1Dev
  • 27
  • 6

1 Answers1

0

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);

    }
}));
cello
  • 5,356
  • 3
  • 23
  • 28