Java - 获得表单焦点时的大写锁定状态

Java - Caps Lock status on form focus gained

好吧,我有以下代码来检查大写锁定的状态,当我在表单中使用 focu 更改大写锁定的状态时没有问题,但是当我最小化表单并更改大写状态时lock 和 back 最大化窗体不更新 caps lock 的状态。有什么想法吗?

/**
 *
 * @author joepa37
 */
public class FocusExample extends javax.swing.JFrame {

    public FocusExample() {
        initComponents();
    }

    @SuppressWarnings("unchecked")                     
    private void initComponents() {

        capsLockLbl = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridLayout());

        capsLockLbl.setText("CAPS LOCK : ");
        getContentPane().add(capsLockLbl);

        pack();
    }                    

    private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_CAPS_LOCK) {
            updateStatus();
        }
    }                               

    private void formFocusGained(java.awt.event.FocusEvent evt) {                                 
        updateStatus();
    }                                

    private void updateStatus(){
        boolean isCapsLockOn = java.awt.Toolkit.getDefaultToolkit ().getLockingKeyState ( java.awt.event.KeyEvent.VK_CAPS_LOCK );
        capsLockLbl.setText(isCapsLockOn ? "CAPS LOCK ON" : "CAPS LOCK OFF");
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FocusExample().setVisible(true);
            }
        });
    }

    private javax.swing.JLabel capsLockLbl;         
}

我找到了一个解决方案,不是很专业,但很管用。我所做的是添加一个机器人,以便在表格成为焦点时按次大写锁定。两次return到用户上次离开的原始状态,显然它完美地更新了事件。

this.addWindowListener(new WindowAdapter() {
    @Override
    public void windowActivated(WindowEvent we) {
        try {
            java.awt.Robot r = new java.awt.Robot();

            //first time to update the event
            r.keyPress(KeyEvent.VK_CAPS_LOCK);
            r.keyRelease(KeyEvent.VK_CAPS_LOCK);

            //second time to return to the last time status
            r.keyPress(KeyEvent.VK_CAPS_LOCK);
            r.keyRelease(KeyEvent.VK_CAPS_LOCK);

        } catch (Exception e) {}

      updateStatus();

    }
}
);