Button not responding to enter key stroke..
Hi all,
I have a swing application, with some buttons. User can move the focus using tab key. When a focus is on a button and if the user hits enter key, it is not invoking the click action of the button. But when I press space key it is working. But the same application is working fine in Windows.
What could be the problem?
Thanks.
# 5
Hi boss,
You can do one thing... add the following class in your project and replace JButton word with MyButton in all your classes which uses JButton...
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MyButton extends JButton implements KeyListener {
private static final long serialVersionUID = 1;
public static void main(String shail[]) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
MyButton button = new MyButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Yes");
}
});
frame.add(button);
frame.setBounds(100, 100, 800, 600);
frame.setVisible(true);
}
public MyButton() {
this.addKeyListener(this);
}
public MyButton(Action arg0) {
super(arg0);
this.addKeyListener(this);
}
public MyButton(Icon arg0) {
super(arg0);
this.addKeyListener(this);
}
public MyButton(String arg0) {
super(arg0);
this.addKeyListener(this);
}
public MyButton(String arg0, Icon arg1) {
super(arg0, arg1);
this.addKeyListener(this);
}
public void keyPressed(KeyEvent arg0) {
}
public void keyReleased(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
this.fireActionPerformed(new ActionEvent(ke.getSource(),
ke.getID(), this.getText()));
}
}
public void keyTyped(KeyEvent arg0) {
}
}
let me know if it works... OK ... enjoy...