Reputation: 15251
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"));
Upvotes: 3
Views: 2979
Reputation: 57421
Use KeyBindings http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
Upvotes: 3
Reputation: 109823
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()
;
Upvotes: 5
Reputation: 115388
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
Upvotes: 5