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