How to Move Between Frames in Java
GUI components in Java use focus events and focus listeners to determine when their windows is currently the "active" window, which determines whether it handles input from the keyboard. To gain this focus, a window must call either inherited method "requestFocus()" or "toFront()". The former gives the window keyboard input, and the latter puts the window on top of other windows. Java's two "frame" classes, Frame and JFrame, are both components that can request focus for themselves or pass focus on to another frame.
Instructions
-
-
1
Call the "requestFocus()" or "toFront()" method when you want a frame to draw focus, as in "myFrame.requestFocus();"
-
2
Attach a FocusListener to the frame. If you have an instance of JFrame called "myFrame," this is done at the beginning with the following code: "myFrame.addFocusListener (new FocusListener() { void focusGained(FocusEvent e) { } } );"
-
-
3
Define the focusGained method so that if any other action is to be taken when the focus changes, it is done.
-
4
Repeat Step 1 through Step 3 with other frame instances.
-
1
Tips & Warnings
If you are switching between components in a single window, use the method "requestFocusInWindow()" instead of "requestFocus()"
Not all requests for focus can be granted immediately. Use focusGained to set a flag to tell your program when the frame actually gains focus. As Swing components are not thread-safe, this flag should be declared as a volatile data type.
References
- Photo Credit Comstock/Comstock/Getty Images