支持复制选项
Posted
技术标签:
【中文标题】支持复制选项【英文标题】:Support for COPY option 【发布时间】:2015-11-16 14:41:41 【问题描述】:我正在 NetBeans 中编写 Java Swing 计算器。我有 JFrame、计算器按钮和名为 display 的 JTextField。我需要支持复制(以及 CTRL+C)选项。有谁知道如何做到这一点?
【问题讨论】:
您的意思是复制到剪贴板吗?之前已经回答过很多次了,例如here 【参考方案1】:如果您想为剪切/复制/粘贴添加右键菜单,您可以使用组件已有的剪切/复制/粘贴操作,尽管我更喜欢重命名它们以使它们更易于阅读,因为“剪切”比“剪切到剪贴板”更容易阅读。
例如,如果您调用此方法并传入任何文本组件,它应该添加一个右键弹出菜单用于剪切-复制-粘贴:
// allows default cut copy paste popup menu actions
private void addCutCopyPastePopUp(JTextComponent textComponent)
ActionMap am = textComponent.getActionMap();
Action paste = am.get("paste-from-clipboard");
Action copy = am.get("copy-to-clipboard");
Action cut = am.get("cut-to-clipboard");
cut.putValue(Action.NAME, "Cut");
copy.putValue(Action.NAME, "Copy");
paste.putValue(Action.NAME, "Paste");
JPopupMenu popup = new JPopupMenu("My Popup");
textComponent.setComponentPopupMenu(popup);
popup.add(new JMenuItem(cut));
popup.add(new JMenuItem(copy));
popup.add(new JMenuItem(paste));
例如:
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class AddCopyAndPaste extends JPanel
private JTextField textField = new JTextField("Four score and seven years ago...");
private JTextArea textArea = new JTextArea(15, 30);
public AddCopyAndPaste()
addCutCopyPastePopUp(textField);
addCutCopyPastePopUp(textArea);
setLayout(new BorderLayout());
add(textField, BorderLayout.PAGE_START);
add(new JScrollPane(textArea), BorderLayout.CENTER);
// allows default cut copy paste popup menu actions
private void addCutCopyPastePopUp(JTextComponent textComponent)
ActionMap am = textComponent.getActionMap();
Action paste = am.get("paste-from-clipboard");
Action copy = am.get("copy-to-clipboard");
Action cut = am.get("cut-to-clipboard");
cut.putValue(Action.NAME, "Cut");
copy.putValue(Action.NAME, "Copy");
paste.putValue(Action.NAME, "Paste");
JPopupMenu popup = new JPopupMenu("My Popup");
textComponent.setComponentPopupMenu(popup);
popup.add(new JMenuItem(cut));
popup.add(new JMenuItem(copy));
popup.add(new JMenuItem(paste));
private static void createAndShowGui()
AddCopyAndPaste mainPanel = new AddCopyAndPaste();
JFrame frame = new JFrame("Add Copy And Paste");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
public void run()
createAndShowGui();
);
【讨论】:
以上是关于支持复制选项的主要内容,如果未能解决你的问题,请参考以下文章