Overriding JComponent’s Ctrl-C Action

A little Java geekery here for my own reference and anyone else that needs it….

I needed to override the default CTrl-C (copy) behavior on a JList (though this should work on any JComponent) to copy what I wanted to the clipboard. After Googling and playing with it, I found that this works:

InputMap im = JLIST.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap am = JLIST.getActionMap();
Action copyAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
String myString = "this goes to clipboard";
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(new StringSelection(myString ), null);
}
};
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK), "Copy");
am.put("Copy", copyAction);

Leave a Reply

Your email address will not be published. Required fields are marked *