Simple KeyListener not working

冷暖自知 提交于 2019-12-04 06:22:35

问题


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



来源:https://stackoverflow.com/questions/13919622/simple-keylistener-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!