2

I'm trying to create an application so when the user tries to enter a capslock letter in a JTextfield or something it will bring up an error informing the user to turn off the capslock.

import java.awt.*;
import java.awt.event.*;

public class NewClass
{
    private static String check="false";

    public static void main(String[] args)
    {
        if ( Toolkit.getDefaultToolkit().getLockingKeyState (KeyEvent.VK_CAPS_LOCK ) );
        check="true";

        if(check.equals(true));
        System.out.println("Turn it off");
        {
        }
    }

How can I use a boolean with

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

so if it's true show message to turn it off?

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
JOHN
  • 33
  • 6

4 Answers4

3

this

if(check.equals(true));

should be

if(check.equals("true"))

and remove the ; from the first if-statement, although all you really need to do is

if(Toolkit.getDefaultToolkit().getLockingKeyState (KeyEvent.VK_CAPS_LOCK ))
{
     System.out.println("Turn it off");
}
mre
  • 43,520
  • 33
  • 120
  • 170
2

This should work!

boolean state= Toolkit.getDefaultToolkit()
                    .getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
WhatisSober
  • 988
  • 2
  • 12
  • 32
2

This should work

if (Toolkit.getDefaultToolkit().getLockingKeyState(
        KeyEvent.VK_CAPS_LOCK)) {
    check = "true";
}
if (check.equals("true")) {
    System.out.println("Turn it off");
}

Things that were wrong in your code,

1) Semicolon in the if statement. Remember if there is a semicolan at the end of If the if block wont execute.

   if (true); {
     // wont be executed
   }

   if (true) {
     // will be executed    
   }

2) The comparison is wrong. It should be. If you had defined the "check" variable as boolean your old code is fine. Since you are using them as String you should equate as below. I advise you to use boolean type there.

if (check.equals("true"))
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
0

You should not only look at CapsLock because someone could press the shift key to enter an upper case letter. Add a key listener to the JTextField and inspect the typed letter. You could even change the upper case letter to lower case.

    final JTextField jTextField = new JTextField() {
        {
            addKeyListener(new KeyListener() {
                public void keyTyped(final KeyEvent e) {
                    System.out.println(e.getKeyChar());
                    System.out.println(e.getModifiers());
                }
                public void keyReleased(final KeyEvent e) {
                }
                public void keyPressed(final KeyEvent e) {
                }
            });
        }
    };
Java42
  • 7,628
  • 1
  • 32
  • 50