Allain Lalonde
Allain Lalonde

Reputation: 93348

How can I detect if caps lock is toggled in Swing?

I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on.

Is this possible? And if so I'd like to have it detected before the client types their first letter.

Is there a non-platform specific way to do this?

Upvotes: 17

Views: 6329

Answers (3)

StephMW
StephMW

Reputation: 78

In addition to Nick's answer, to react to this condition before the user presses a key, you can listen to the focus event of your text entry component and test the caps-lock as the component receives focus.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630439

Try this, from java.awt.Toolkit, returns a boolean:

Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)

Upvotes: 27

Related Questions