在面板中按下ENTER键时执行JButton - Swing

时间:2014-02-06 06:25:34

标签: java swing jbutton keyevent

我在面板上有登录 JButton,当我按 ENTER 键时我需要执行它。

我们有任何代码片段吗?

2 个答案:

答案 0 :(得分:2)

您可以使用InputMapActionMap来执行此操作。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ac1
{
    public static void main(String args[])
    {
    JFrame f=new JFrame();
    f.setVisible(true);
    f.setSize(400,400);
    f.setLayout(new FlowLayout());

    final JButton b=new JButton("button");
    f.add(b);



f.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDO

W).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"clickButton");

f.getRootPane().getActionMap().put("clickButton",new AbstractAction(){
        public void actionPerformed(ActionEvent ae)
        {
    b.doClick();
    System.out.println("button clicked");
        }
    });
    }
}

答案 1 :(得分:1)

要初步关注按钮,您可以执行以下操作:

frame.getRootPane().setDefaultButton(buttonName);
buttonName.requestFocus();

//或者您可以将Enter密钥绑定到JComponentJButton

AbstractAction action = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() instanceof JButton){
        JButton button = (JButton) e.getSource();
        button.doClick();        
        } else if(e.getSource() instanceof JComponent){
            JComponent component = (JComponent) e.getSource();
            component.transferFocus();
        }
    }
    };

//您可以将键绑定到JComponent,如:

jComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "TransferFocus");
jComponent.getActionMap().put("TransferFocus", action);

//您可以将键绑定到JButton,如:

jButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "DoClick");
jButton.getActionMap().put("DoClick", action);

有用的链接

How to Use the Focus Subsystem