CN1002
CN1002

Reputation: 1115

Toggle Caps Lock On Tooltip on JTextField

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();

          }
      });
   }
}

Upvotes: 2

Views: 783

Answers (1)

Tim B
Tim B

Reputation: 41188

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.

Upvotes: 3

Related Questions