How to Reset the Focus in Java
The Abstract Window Toolkit (AWT) is a hierarchy of classes defined in the standard library for the Java programming language. Using AWT, a Java program can create and manage the components that define a graphical user interface (e.g., windows, text fields, images) and their relationships. At any given time, one window and one component within that window have focus: the window is displayed on top of other windows, and the component receives keyboard and mouse actions. Your Java code can reset the focus to any component and its containing window at any time.
Instructions
-
-
1
Include the following lines at the beginning of your Java code:
import java.awt.*;
import javax.swing.*;
-
2
Create the window to which you want to give focus, and the component within that window that will receive focus, as in the following sample code:
public MyGraphicApp extends JFrame {
private JTextField myTextField;
private GroupLayout myLayout;
public MyGraphicApp() {
myLayout = new GroupLayout(getContentPane());
getContentPane().setLayout(myLayout);
myTextField = new JTextField();
SequentialGroup sg = myLayout.createSequentialGroup();
sg.addComponent(myTextField);
}
}
When, as in the example, your class extends Java library's JFrame, you can concentrate on defining the components that make your application unique while inheriting all basic Swing components and mechanisms from the Java library. The sample class has a single window with a single component, that is a field inside of which the user can type text.
-
-
3
Give focus to the component you want to have it, and by extension to its containing window (the top-level ancestor in the component hierarchy), as in the following sample code:
myTextField.requestFocusInWindow();
Different components show that they have focus in different ways. For example, a text field will show a blinking cursor ready to take input, and a window will be displayed on top of all other windows on the desktop.
-
1
References
- Photo Credit Thinkstock Images/Comstock/Getty Images