简体   繁体   English

如何在Java中制作带有项目以复制文本的JPopupMenu

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

I want to know how to make a JPopupMenu that has an item to copy text. 我想知道如何制作一个具有复制文本项的JPopupMenu。 I have started with putting the label with a JPopupMenu. 我首先使用JPopupMenu放置标签。

What is the code for this item "Copy" in the JPopupMenu to copy the text? JPopupMenu中用于复制文本的“复制”项的代码是什么?

The following should get you started: Add a JMenuItem to the popup with the copy command. 以下内容将帮助您入门:使用copy命令将JMenuItem添加到弹出窗口。 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: actionPerformed方法中,获取要复制的文本,然后将其传递到可以使用Java中的Toolkit类获取的系统剪贴板:

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

    }
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM