按下按钮后的KeyListener

时间:2014-11-19 20:08:41

标签: java actionlistener keylistener

我正在创建一个小应用程序,如果按下大写锁定按钮,将添加一个托盘图标。我收到的错误似乎无法解决。

这是我的代码

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {       

    public void keyPressed(KeyEvent ke){

        //removed for StackOverflow

    }

 }   

我在keyPressed Listener上遇到“非法表达式启动”错误 现在这可能是一个非常简单的修复,我只是不知道。

2 个答案:

答案 0 :(得分:2)

正如一些评论者所述,请改用KeyListener

public class CtrlToIconListener implements KeyListener {

  private boolean displayed = false;

  // consumed
  public void keyTyped(KeyEvent e) {}

  // when the key is first pressed
  public void keyPressed(KeyEvent e) {

    // if the control key is pressed, handled it.
    if (e.getKeyCode() == KeyEvent.VK_CAPS_LOCK) {
      displayed = !displayed;
    }
  }

  // when the key is released
  public void keyReleased(KeyEvent e) {

    // do something clever
  }

}

然后你将这个类用作jFrame的监听器(我假设你正在使用它)

更多信息: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

答案 1 :(得分:1)

KeyListener只有在注册的组件具有焦点且具有焦点时才会被激活。如果UI有一些其他组件(如按钮或文本字段),那么它将无法工作。

我假设您想知道大写锁定状态更改的时间,无论您的程序中有什么焦点。为此,您可以使用AWTListener注册Toolkit并监控应用程序处理的所有关键流量。

使用此侦听器,您可以监视KeyEvent.VK_CAPS_LOCK键事件并采取适当的操作。

如果您需要知道大写锁定键的确切状态,可以使用Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)确定它是否开启......

import java.awt.AWTEvent;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestListener {

    public static void main(String[] args) {
        new TestListener();
    }

    public TestListener() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel capsStateLabel;

        public TestPane() {
            setLayout(new GridBagLayout());
            capsStateLabel = new JLabel();
            add(capsStateLabel);
            updateLabelState();
            Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

                @Override
                public void eventDispatched(AWTEvent event) {
                    if (event instanceof KeyEvent) {

                        KeyEvent ke = (KeyEvent) event;
                        switch (ke.getKeyCode()) {
                            case KeyEvent.VK_CAPS_LOCK:
                                switch (ke.getID()) {
                                    case KeyEvent.KEY_PRESSED:
                                    case KeyEvent.KEY_RELEASED:
                                        updateLabelState();
                                        break;
                                }
                                break;
                        }

                    }
                }

            }, KeyEvent.KEY_EVENT_MASK);
        }

        protected void updateLabelState() {
            boolean capsState = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
            if (capsState) {
                capsStateLabel.setText("Caps is ON");
            } else {
                capsStateLabel.setText("Caps is OFF");
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}