Java Swing: How to prevent system copy,cut,paste action?
-
26-10-2019 - |
Question
So I am trying to prevent the user from being able to use the default system actions by pressing control + C, control + X, control + V.
I want anywhere inside this particular scrollPane, to catch the key. The scrollPane loads a Component into itself, for example JLabel.
scrollPane.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent evt) {
if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_C) {
System.out.println("disabled");
} else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_X) {
System.out.println("disabled");
} else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {
System.out.println("disabled");
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
However, nothing is being printed.
I added the same keylistener to a Jtree but it's working for that.
UPDATE:
So using keybinds, how do I get a JoptionPane to appear?
scrollPane.getInputMap(JComponent.WHEN_FOCUSED)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK),
JOptionPane.showMessageDialog(null, "disabled"));
Solution
better would be implements KeyBindings rather than KeyListener, because
1) KeyListener
works only when JComponent
has Focus
in the Window,
2) you set KeyListener
to JScrollPane
instead of JTree
3) for KeyBindings you can set InputMap and ActionMap for
to the TopLevel Container (
JFrame, JDialog, JWindow
)concrete
JComponent
(s)
4) for KeyListener
and KeyBindings
this TopLevel Container must have Focus on the Screen
5) then you can set for required event(s)#consume()
;
OTHER TIPS
You should attach your custom TransferHandler that will override getCutAction
and getCopyAction
to your all instances of JComponent you want to prevent from user's copy/paste.
Please take a look here for details: http://docs.oracle.com/javase/1.5.0/docs/guide/swing/1.4/dnd.html#ClipboardTransferSupport