If you can use them, key bindings are easier to handle with regards to focus:
http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
but if you can't use those then you could call requestFocusInWindow() on the JApplet (or whatever other container you need to have focus) at the end of your button listener code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class FocusTest extends JApplet {
JButton button;
public void init() {
button = new JButton("Ok");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
requestFocusInWindow();
}
});
setLayout(new BorderLayout());
add(button,BorderLayout.SOUTH);
setFocusable(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
JOptionPane.showMessageDialog(FocusTest.this, "Key pressed");
}
});
}
}
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847