If you can use them, key bindings are easier to handle with regards to focus:
http://java.sun.com/docs/books/tutor...eybinding.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");
}
});
}
}
Moderator
Featured Poster
Reputation Points: 3239
Solved Threads: 838
Posting Genius
Offline 6,761 posts
since May 2007