Java - 获得表单焦点的Caps Lock状态

时间:2015-01-16 06:35:55

标签: java focus frame

好吧,我有以下代码来检查大写锁定的状态,当我在表单中更改大写字母的状态时没有问题,但是当我最小化表单并更改大写锁定的状态时返回最大化表单不更新大写锁定的状态。有什么想法吗?

/**
 *
 * @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;         
}

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,不是那么专业但是有效。我所做的就是添加一个机器人,以便在表格成为焦点时按下时间。两次返回到用户最后一次离开的原始状态,显然它会完美地更新事件。

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

    }
}
);