Reputation: 13
I'm building simple chat application with simple GUI, but a I have a problem assigning Enter key to Send button. Right now it is quite unpractical pressing Alt+Enter.
public void buildInterface() {
//some other components
btnSend = new JButton("Send");
btnExit = new JButton("Exit");
btnSearch=new JButton("Search");
btnSend.setMnemonic(KeyEvent.VK_ENTER);
JPanel box=new JPanel();
add(box, BorderLayout.SOUTH);
box.add(tfInput);
box.add(btnSend);
box.add(btnExit);
box.add(btnSearch);
}
Upvotes: 0
Views: 968
Reputation: 99
Add following code to your Util class
public static void bindKeyStroke(final JButton btn, String ks) {
final ActionListener[] alist = btn.getActionListeners();
if (alist.length != 0) {
AbstractAction action = new AbstractAction(btn.getText(), btn.getIcon()) {
@Override
public void actionPerformed(ActionEvent e) {
for (ActionListener al : alist) {
ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), Action.ACCELERATOR_KEY);
al.actionPerformed(ae);
}
}
};
KeyStroke keyStroke = KeyStroke.getKeyStroke(ks);
btn.setAction(action);
btn.getActionMap().put(Action.ACCELERATOR_KEY, action);
btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, Action.ACCELERATOR_KEY);
}
}
Goto frame, dialog or panel constructor and add after initComponent();
Util.bindKeyStroke(<your button>, "alt enter");
Fix double action, in action performed
if (evt.getActionCommand().equals(Action.ACCELERATOR_KEY)) {
// Your send action here
}
Upvotes: 1
Reputation: 347214
When the button is focused, under most look and feels the Enter will activate the button.
You can, however, assign a button to be the "default" button for the window, which will be activated when the Enter key pressed, so long as the focused component does not consume it.
See How to Use Root Panes and JRootPane#setDefaultButton
for more details
Upvotes: 1