动作监听器,键盘输入

时间:2014-01-18 07:25:16

标签: java swing action actionlistener

我遇到了动作侦听器的问题。 问题是:

 private static void createAndShowGUI() {
    int i;
    System.out.println("Created GUI on EDT? "+
    SwingUtilities.isEventDispatchThread());
    JFrame f = new JFrame("Best Game Ever");        
    JButton buttonA = new JButton("Press 'z'");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.add(new MyPanel(),BorderLayout.CENTER);
    f.add(buttonA, BorderLayout.PAGE_END);      
    f.pack();
    f.setVisible(true);
    final char ACTION_KEY = 'z';
    final char ACTION_KEY2 ='x';
    Action actionListener = new AbstractAction()
    {          
        public void actionPerformed(ActionEvent actionEvent)
        {
        }
    };

    Action actionListener2 = new AbstractAction()
    {          
        public void actionPerformed(ActionEvent actionEvent)
        {
            System.out.println("x");
        }
    };      
    KeyStroke z = KeyStroke.getKeyStroke('z');       
    InputMap inputMap = buttonA.getInputMap();
    inputMap.put(z, ACTION_KEY);
    ActionMap actionMap = buttonA.getActionMap() ;
    actionMap.put(ACTION_KEY, actionListener);        
    KeyStroke x = KeyStroke.getKeyStroke('x');
    InputMap inputMap2 = buttonA.getInputMap();
    inputMap2.put(x, ACTION_KEY2);
    ActionMap actionMap2 = buttonA.getActionMap();
    actionMap2.put(ACTION_KEY2, actionListener2);        
} 

我只是不能为它编制一个代码,即使我按住键也只能打印一次。 感谢。

抱歉没有把所有代码:(

希望现在能有所作为。

1 个答案:

答案 0 :(得分:1)

  

“即使拿着钥匙,我也只能为它编制代码才能打印一次。”

一种方法是将released添加到kestroke,它只会在密钥被释放时打印

   inputMap.put(KeyStroke.getKeyStroke("released X"), "printX");
  

KeyStroke表示键盘或等效输入设备上的键操作。 KeyStrokes只能对应于特定键的按下或释放,就像KEY_PRESSED和 KEY_RELEASED KeyEvents一样;或者,它们可以对应于键入特定的Java字符,就像KEY_TYPED KeyEvents那样。

Here's an example
import java.awt.event.ActionEvent;
import javax.swing.*;

public class TestKeyBind {

    public TestKeyBind() {
        JPanel panel = new JPanel();

        Action actionListener2 = new AbstractAction() {
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("x");
            }
        };
        InputMap inputMap = panel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = panel.getActionMap();

        inputMap.put(KeyStroke.getKeyStroke("released X"), "printX");
        actionMap.put("printX", actionListener2);

        JFrame frame = new JFrame();
        frame.add(panel);
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestKeyBind();
            }
        });
    }
}

您也可以尝试typed,但每个平台都会运行“键入类型”事件。它不适用于Windows,我只是尝试过它