Swing
Focus
Review the focus specification and focus tutorial.
When needing to control focus on window/dialog open, if possible,
avoid the use of requestFocus
completely and use a custom
FocusTraversalPolicy
with an overridden getDefaultComponent.
Otherwise, use requestFocusInWindow
instead of requestFocus
or grabFocus:
requestFocus(): Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow().
grabFocus(): Client code should not use this method; instead, it should use requestFocusInWindow().
In general, avoid performing cross-window focus requests:
There is no foolproof way, across all platforms, to ensure that a window gains the focus. [...] 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. Alternatively, you can apply a custom FocusTraversalPolicy to the frame and call the getDefaultComponent method to determine which component will gain the focus.
Hello World
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class SwingHelloWorld {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingHelloWorld().createAndShowMainFrame();
}
});
}
private int clicked = 0;
private void createAndShowMainFrame() {
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel label1 = new JLabel("Hello World");
label1.setBorder(new EmptyBorder(10, 10, 10, 10));
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel label2 = new JLabel("Clicked: " + clicked);
label2.setBorder(new EmptyBorder(10, 10, 10, 10));
label2.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton button = new JButton("Button");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label2.setText("Clicked: " + (++clicked));
}
});
panel.add(label1);
panel.add(button);
panel.add(label2);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}