我在NetBeans中编写Java Swing计算器。我有JFrame,计算器按钮和JTextField称为显示。我需要支持复制(以及CTRL+C)选项。有人知道怎么做吗?
如果您想为剪切/复制/粘贴添加一个右键菜单,您可以使用组件已经拥有的剪切/复制/粘贴操作,尽管我更喜欢重命名它们以使它们的名称更简单更容易阅读,因为"剪切"比"剪切到剪贴板"更容易阅读。
例如,如果你调用这个方法并传入任何文本组件,它应该为cut-copy-paste添加一个右键弹出菜单:
// 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();
}
});
}
}