2

I want to warn a user when caps lock is on the way it is done on Windows when login. I have a JTextField where this should be shown. I have searched forums and found out that the check if the key is on or off we use Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK). However, I am not sure how to attach this to the text field.

Note: I do not want to pop up a dialog with the message that the caps lock is on.

Question: How do I show caps lock warning/tool tip on a JTextField?

Here is my code:

public class CapsLockWarningJTextField {

private JFrame frame;

CapsLockWarningJTextField() {
    frame = new JFrame();
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new net.miginfocom.swing.MigLayout());
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);

    JTextField t = new JTextField(10);

    // if (Toolkit.getDefaultToolkit().getLockingKeyState(
    // KeyEvent.VK_CAPS_LOCK)) {
    // t.setToolTipText("Caps Lock ON");
    // }

    frame.add(t, "cell 0 0");

}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new CapsLockWarningJTextField();

          }
      });
   }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
CN1002
  • 1,115
  • 3
  • 20
  • 40
  • possible duplicate of [How can I get the Caps Lock state, and set it to on, if it isn't already?](http://stackoverflow.com/questions/7435221/how-can-i-get-the-caps-lock-state-and-set-it-to-on-if-it-isnt-already) – Mordechai Apr 24 '15 at 08:41
  • @MouseEvent Well, I do not want it that way. These questions are different! I want it to be shown on the way it is done on Windows when login in - the way it is shown [here](http://guijournal.com/wp-content/uploads/2011/07/Win7-password-Caps-Lock.png)! – CN1002 Apr 24 '15 at 08:49

1 Answers1

3

By following the advice in this question: Value Change Listener to JTextField you can add a listener to your jTextField.

In that listener you can check if caps lock is on whenever the document changes and warn them if it is. You would most likely want to set a flag as well so you only display the warning once, they may want to enter some or all of the password in caps.

Community
  • 1
  • 1
Tim B
  • 40,716
  • 16
  • 83
  • 128
  • Well this is working, thanks. I would play around with the labels to display the the desired icons as shown [here](http://guijournal.com/wp-content/uploads/2011/07/Win7-password-Caps-Lock.png). – CN1002 Apr 24 '15 at 10:07