Layout managers

How a window places its components without fixed coordinates: flow, row and column, border, grid, stack and anchored layouts, nesting of containers and behavior when resized.

  • 29 cards
  • 3 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link

A few cards from the deck

  • Container: what is it?

    Show the answer

    A component whose role is to hold others and place them; it can itself be placed inside another of its kind.

    A window is a tree of containers: each has its own layout, and simple components (button, field) are the leaves.

  • Why not place components with fixed pixel coordinates?

    • Because the window size, the font and the language change the space needed
    • Because Java refuses to display a component without a layout manager
    • Because fixed coordinates slow down drawing the window
    • Because a component placed in pixels no longer receives clicks
    Show the answer

    Because the window size, the font and the language change the space needed

    A label changes length when translated (“Save” becomes “Enregistrer” in French), a larger font overflows, a smaller window clips. A layout manager recomputes all of that at every display. Pixel placement is still possible (setLayout(null) then setBounds in Swing), but it is brittle.

  • In Swing, a JPanel uses a … layout by default, whereas a JFrame's content uses a … layout.

    Show the answer

    In Swing, a JPanel uses a flow layout by default, whereas a JFrame's content uses a border layout.

    Hence the classic trap: in a JFrame, add(component) without a constraint puts the component in the center, and the next one replaces it.

  • Layout manager: what is it?

    Show the answer

    An object attached to a host component that computes the position and size of each component according to a rule, at every display and resize.

    The programmer describes constraints (“at the top”, “across the full width”) rather than pixels: the manager adapts to the window size, the font and the language.

  • What does this Swing JFrame show, with its default layout?

    ```java
    JFrame fenetre = new JFrame("Test");
    fenetre.add(new JButton("A"));
    fenetre.add(new JButton("B"));
    fenetre.pack();
    fenetre.setVisible(true);
    `

    • Buttons A and B side by side on a row
    • Only button B, filling the whole center
    • Button A above button B
    • Buttons A and B stacked, with A visible
    Show the answer

    Only button B, filling the whole center

    A JFrame's content uses a border layout and add without a zone targets the center. Only one component fits in a zone: B replaces A. To put them side by side, add both to a JPanel, which is flow by default.