KeyListener not working

假如想象 提交于 2019-11-28 14:41:18

Let's start with the fact that you're not attached the listener to anything, then move on to the fact that you really should be using Key Bindings

And with example

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTableEditing {

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

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

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

    public class TestPane extends JPanel {

        private JLabel key;
        private int counter = 0;

        public TestPane() {
            key = new JLabel("...");
            add(key);
            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "A.pressed");
            am.put("A.pressed", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("A was pressed");
                    key.setText("A was pressed " + (++counter));
                }
            });
        }

    }

}

I know this is an old post but I wanted to put this online so someone like myself can find it....

I worked on this problem for hours before figuring it out. Make sure that your Component has focus. For example I have all of my activity going on in a custom JPanel named SpaceShipPanel:

class SpaceShipPanel
{
    //instance variables
    //Now my constructor
    SpaceShipPanel(){
        //bla bla blah
        setFocusable(true);//THIS LINE IS WHAT SAVED ME!!
    }
}

From what I hear, keyBindings are the best route but the class I'm taking didn't cover this topic. Hopefully this will save someone hours of beating their heads against the wall.

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