-->

Simple KeyListener not working

2020-05-03 05:20发布

问题:

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.

Here is my code:

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

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");
    }
}

回答1:

A JPanel cannot gain focus for KeyListener to work.

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.

Key Binding Example



回答2:

  • JPanel isn't focusable JComponent, have to add Object/JComponents that is focusable or interact with KeyEvents

  • KeyListener isn't proper listener for Swing JComponents, for Swing is replaced with KeyBindings



回答3:

I had similar problem but its so simple to solve but you have to found how to solve it witch is not so easy task :D

so how to solve this ? I just set all my buttons as focusable false. instanceOfYourButton.setFocusable(false); thats it