简单的 KeyListener 不起作用

2022-01-24 00:00:00 java swing jframe keylistener

我正在开发一个非常简单的 Java 项目,试图了解如何使用 KeyListener.我创建了一个 Main 类和一个 KeyListener、MouseListener 类.当我按下键盘键时,我想发生一些事情.到目前为止,当我单击时,唯一有效的是你好".

I'm working on a really simple project in Java to try to understand how to use KeyListener. I've created a Main class and a KeyListener, MouseListener class. I want to get something to happen when I press a keyboard key. So far the only thing that is working is "Hello" when I click.

这是我的代码:

import javax.swing.JFrame;
import javax.swing.JPanel;

public class KeyPractice{

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        panel.addKeyListener(new KeyEar());
        panel.addMouseListener(new KeyEar());

        frame.add(panel);

        frame.setVisible(true);
        frame.setSize(400, 400);
    } 
}

还有 Keylistener 类....

And the Keylistener class....

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class KeyEar implements KeyListener, MouseListener {

    public KeyEar(){

    }

    @Override
    public void mouseClicked(MouseEvent arg0) {
        System.out.println("Hello");
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        System.out.println("Hello");
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        System.out.println("Hello");
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        System.out.println("Hello");
    }
}

推荐答案

JPanel 无法获得焦点以使 KeyListener 工作.

A JPanel cannot gain focus for KeyListener to work.

首选方法是对 Swing 使用 键绑定.即使组件没有焦点,您也可以将 Action 映射到 KeyStroke.

The preferred approach is to use Key Bindings for Swing. You can map an Action to a KeyStroke even when a component doesn't have focus.

键绑定示例

相关文章