支持COPY选项

时间:2015-08-22 21:17:28

标签: java swing netbeans copy calculator

我在NetBeans中编写Java Swing Calculator。我有JFrame,计算器按钮和名为 display 的JTextField。我需要支持副本(以及CTRL + C)选项。有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分:4)

如果要添加用于剪切/复制/粘贴的右键单击菜单,可以使用组件已有的剪切/复制/粘贴操作,但我更喜欢重命名它们,以便更简单地读取名称,因为它更容易阅读" Cut"而不是"切割到剪贴板"。

例如,如果你调用这个方法并传入任何文本组件,它应该为剪切复制粘贴添加一个右键单击弹出菜单:

// 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();
            }
        });
    }
}