Resize Components
Explore how to keep one component size the same while resizing others on window resizing using component and window listener.
Notifying component and window listener on change of window size
If you allow the window to be resizable, doing so should cause the program to resize the window’s contents by the same relative amount.
A component listener would be notified if the user dragged the edge of the window. A window state listener would be notified if the user maximized or minimized the window, or returned the window to normal state.
Listening to the window when it is resized
WordBuilder will need to respond to events when the window changes size.
- In the listeners section of
initGUI()
, add a component listener to callresizeWindow()
when the window’s frame is dragged to a new size using JFrame’saddComponentListener()
method, with a newComponentAdapter
object as the parameter value. In theComponentAdapter
, add a public method calledcomponentResized()
.componentResized()
should have one parameter, aComponentEvent
, and return nothing. IncomponentResized()
, callresizeWindow()
. - Add a window state listener to call
resizeWindow()
when the window is maximized, or returned to its original state using JFrame’saddWindowStateListener()
method, with a newWindowStateListener
object as the parameter value. In theWindowStateListener
, add a public method calledwindowStateChanged()
.windowStateChanged()
should have one parameter, aWindowEvent
, and return nothing. InwindowStateChanged()
, callresizeWindow()
.
Note: Do not execute the code yet. It will have a syntax error because resizeWindow()
does not exist yet.
...
private void initGUI() {
...
// listeners
addComponentListener(__________________ {
_____________ componentResized(_____________) {
__________();
}
});
addWindowStateListener(__________________ {
_____________ windowStateChanged(_____________) {
__________();
}
});
}
...
Get hands-on with 1200+ tech skills courses.