有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无法成功实现Java密钥绑定

以下是我的项目

public class KeyStrokeExample {

private JFrame jFrame;
private JPanel jPanel;
private JButton jButton;

private Action action;
public static void main(String[] args) {
    KeyStrokeExample keyStrokeExample=new KeyStrokeExample();
    keyStrokeExample.initLayout();
    keyStrokeExample.test();
}

private void initLayout() {
    jFrame=new JFrame("frame");
    jPanel=new JPanel();
    jButton=new JButton("test");

    jPanel.add(jButton);
    jFrame.add(jPanel);

    jFrame.pack();
    jFrame.setVisible(true);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private void test() {
    action=new AbstractAction() {

        public void actionPerformed(ActionEvent e) {
            System.out.println("test");
        }
    };
    int condition = JComponent.WHEN_FOCUSED;
    InputMap inputMap = jPanel.getInputMap(condition);
    ActionMap actionMap = jPanel.getActionMap();

    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK ),"DELETE");
    actionMap.put( "DELETE", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {

            System.out.println("test");

        }
    });
}
}

我从https://tips4java.wordpress.com/2008/10/10/key-bindings/开始练习

我不知道为什么程序不打印“测试”

当我移除

    action=new AbstractAction() {

        public void actionPerformed(ActionEvent e) {
            System.out.println("test");
        }
    };

它可以工作打印测试“

我想知道发生了什么

谢谢


共 (0) 个答案