Force keyboard input in CAPS LOCK onTag(s): IO


import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class Test {
  
  private JFrame myFrame;
  private JTextField myTextField;
  
  public  void doit() {
    myFrame = new JFrame();
    myFrame.setSize(400, 200);
    myFrame.setLocation(100, 100);
    myFrame.setLayout(new java.awt.FlowLayout());
    myTextField = new JTextField(20);
    // Keyboard is CAPSLOCK ON
    java.awt.Toolkit.getDefaultToolkit()
                    .setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
    myFrame.add(myTextField);
      myFrame.addWindowListener( new WindowAdapter() {
        public void windowOpened( WindowEvent e ){
          myTextField.requestFocus();
       }  
      public void windowActivated( WindowEvent e ){
        boolean focus = myTextField.requestFocusInWindow();
        if(focus){
          System.out.println("Focus successful");
        } 
        else{
          System.out.println("Focus unsuccessful");
        }
      }
     }
    );
    myFrame.setVisible(true);  
  }
  
  public static void main(String args[]) {
    new Test().doit();
  }
}

NOTE : This technique changes the keyboard state so the effect is also seen outside the Java program.

See also this related Howto.


blog comments powered by Disqus