我在面板上有登录 JButton
,当我按 ENTER 键时我需要执行它。
我们有任何代码片段吗?
答案 0 :(得分:2)
您可以使用InputMap
和ActionMap
来执行此操作。
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
密钥绑定到JComponent
和JButton
:
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);
有用的链接