views:

46

answers:

1

Is there a way to detect whether Ctrl or Shift has been pressed during a click event on a button or checkbox?

I want to make a checkbox that you have to hold down a modifier key in order to change the state (with appropriate visual labeling) so that it's more difficult to accidentally click it.

+4  A: 

You'll want to use KeyListeners to hook the "key pressed" and "key released" events. Check out this link about key masks to determine if shift or ctrl is pressed (or any key, for that matter).

Dave McClelland
hmm, how do I override the button behavior to handle this? it seems like the actionPerformed() method in the button's ActionListener is too late. (by that point the original event is lost)
Jason S
Take a look at the Oracle link I posted. You should be using `keyPressed` and `keyReleased` functions. Your class should implement `KeyListener`, which should force you to create those functions as well as `keyTyped`, which it sounds like you could just ignore.
Dave McClelland
right, I get that part, but how do I relate it to button/checkbox click events?
Jason S
@Jason Oh, sorry - I guess I didn't understand your question. My thought was that you would have the checkboxes disabled by default, and whenever `shift` or `ctrl` are pressed, you would enable them and on keyRelease you would disable them.You could also check the current keymask when you receive the button's action listener and undo their action if the keys aren't pressed, but that seems awkward.
Dave McClelland
oh! That's an interesting idea, thanks!
Jason S
@Jason Anytime. If you have any additional questions let me know
Dave McClelland