Question: In a Java Swing application I open a JFrame that displays some contents in a JTextArea, and has a Close button (a JButton) at the bottom of the JFrame. I've tried a lot of things, but I can't get initial focus on that JButton component. This is happening on a Mac OS X system, but I'll assume it has the same problem on Windows. Any suggestions?
I found this resource on Sun's web site that states: "A component can also be given the focus programmatically, such as when its containing frame or dialog-box is made visible. This code snippet shows how to give a particular component the focus every time the window gains the focus:"
//Make textField get the focus whenever frame is activated. frame.addWindowListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { textField.requestFocusInWindow(); } });
I tried this, but it actually didn't work. What did work for me is the next tip on that same page, which states "If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed", followed by this code segment (slightly modified for readability):
frame.pack(); //Realize the components. button.requestFocusInWindow(); //This button will have the initial focus. frame.setVisible(true); //Display the window.
Where the first code sample did not put initial focus on my JButton, this code did work.
As one last note, Sun also states in that same resource "Alternatively, you can apply a custom FocusTraversalPolicy to the frame and call the getDefaultComponent method to determine which component will gain the focus." I did not try this in my tests, as the previous code segment did solve my problem.
Follow-up
I probably need to take the time to rewrite this article, but I think I have a better "initial input focus" article in my "How to put initial input focus on a JDialog" tutorial. As I'm working on a new Swing project today, I found that tip to be right on the money for my current initial input focus problem.