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.

  1. In the listeners section of initGUI(), add a component listener to call resizeWindow() when the window’s frame is dragged to a new size using JFrame’s addComponentListener() method, with a new ComponentAdapter object as the parameter value. In the ComponentAdapter, add a public method called componentResized(). componentResized() should have one parameter, a ComponentEvent, and return nothing. In componentResized(), call resizeWindow().
  2. Add a window state listener to call resizeWindow() when the window is maximized, or returned to its original state using JFrame’s addWindowStateListener() method, with a new WindowStateListener object as the parameter value. In the WindowStateListener, add a public method called windowStateChanged(). windowStateChanged() should have one parameter, a WindowEvent, and return nothing. In windowStateChanged(), call resizeWindow().

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.