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"));
better would be implements KeyBindings rather than KeyListener, because
1)
KeyListenerworks only whenJComponenthasFocusin the Window,2) you set
KeyListenertoJScrollPaneinstead ofJTree3) for KeyBindings you can set InputMap and ActionMap for
to the TopLevel Container (
JFrame, JDialog, JWindow)concrete
JComponent(s)4) for
KeyListenerandKeyBindingsthis TopLevel Container must have Focus on the Screen5) then you can set for required
event(s)#consume();