【问题标题】:Adding keylistener or key binding to JButtons that use ActionListener向使用 ActionListener 的 JButton 添加 keylistener 或键绑定
【发布时间】:2013-10-04 16:49:49
【问题描述】:

我需要一些帮助来为下一个示例中的按钮添加按键侦听器或按键绑定。我希望当我在键盘上按下 A 或 B 时,做出与用鼠标按下时相同的动作。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class NetTest {

    static JButton btnA = new JButton("A");
    static JButton btnB = new JButton("B");
    static JPanel jp = new JPanel();
    static JFrame jf = new JFrame("Test APP");
    static JLabel jl = new JLabel("Which button was clicked ?");

    static ActionListener action = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jl.setText(((JButton)e.getSource()).getText());
        }
    };

    public static void main(String[] args) {
        jf.setVisible(true);
        jf.setSize(400, 400);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jp.add(btnA);
        jp.add(btnB);
        jp.add(jl);
        jf.add(jp);

        btnA.addActionListener(action);
        btnB.addActionListener(action);
    }
}

【问题讨论】:

    标签: java swing jbutton keylistener


    【解决方案1】:

    为了收听KeyEvents你需要使用JComponent#getInputMap()JComponent#getActionMap()方法来放置你想收听的输入事件和对应的动作。试试这个例子:

    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class Demo{
    
        private void initGUI(){
            AbstractAction buttonPressed = new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println(e.getActionCommand());
                }
            };
    
            JButton submit = new JButton("Submit");
            submit.addActionListener(buttonPressed);
    
            /*
             * Get the InputMap related to JComponent.WHEN_IN_FOCUSED_WINDOW condition
             * to put an event when A key is pressed
             */
            submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
                    put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,0), "A_pressed");
            /*
             * Add an action when the event key is "A_pressed"
             */
            submit.getActionMap().put("A_pressed", buttonPressed);
    
            /*
             * Same as above when you press B key
             */
            submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
                    put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B,0), "B_pressed");
            submit.getActionMap().put("B_pressed", buttonPressed);
    
            JPanel content = new JPanel(new FlowLayout());
            content.add(new JLabel("Test:"));
            content.add(submit);
    
            JFrame frame = new JFrame("Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(content);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new Demo().initGUI();
                }
            });
    
        }
    }
    

    注意:此示例在按下 JButton 或 A/B 键时使用相同的 AbstractAction,但输出将取决于谁是事件源。

    注意 2: 如果您使用JComponent.WHEN_IN_FOCUSED_WINDOW 条件,您的操作将在按下键 A 或 B 时执行。当您有诸如JTextfieldJTextArea 之类的文本输入组件并且最终用户几乎肯定会多次按下A 或B 键时,不需要这种行为。如果是这种情况,那么您将不得不使用JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 条件。

    【讨论】:

    • dic19 我按照你所说的保存按钮完成了我的功能。这是我的代码。但它对我不起作用。我在这里添加了我的代码。请检查并帮助我。AbstractAction buttonPressed = new AbstractAction(){ @Override public void actionPerformed(ActionEvent e2) { System.out.println(e2.getActionCommand()); } }; buttonSave.addActionListener(buttonPressed); buttonSave.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,0), "保存"); buttonSave.getActionMap().put("save", buttonPressed);
    【解决方案2】:

    如果我理解你想要实现的目标,基本上你想监听两个特定的键盘事件(键“A”或“B”被按下),并切换标签,就像你点击了两个 JButton 之一一样。

    您只需将 KeyListener 添加到框架中,并实现其回调以响应仅键入的“A”或“B”。 还记得在你的 JFrame 对象上调用 setFocusable(false)

        jf.setFocusable(true);
        jf.addKeyListener( new KeyListener() {
    
            @Override
            public void keyTyped( KeyEvent evt ) {
            }
    
            @Override
            public void keyPressed( KeyEvent evt ) {
            }
    
            @Override
            public void keyReleased( KeyEvent evt ) {
            }
        } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 2018-06-10
      • 2012-06-07
      • 1970-01-01
      相关资源
      最近更新 更多