I have Login JButton
on a panel and I need to execute it when I press ENTER key.
Do we have any code snippet for that?
I have Login JButton
on a panel and I need to execute it when I press ENTER key.
Do we have any code snippet for that?
To have initial focus on your button you can do something like this:
frame.getRootPane().setDefaultButton(buttonName);
buttonName.requestFocus();
//Or you can bind your Enter
key to JComponent
and JButton
as:
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();
}
}
};
//You can bind key to JComponent like:
jComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "TransferFocus");
jComponent.getActionMap().put("TransferFocus", action);
//You can bind key to JButton like:
jButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "DoClick");
jButton.getActionMap().put("DoClick", action);
Useful Link
You can use InputMap
and ActionMap
to do this.
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");
}
});
}
}