Chapter 9 · Simulation

Swing Layout Managers

← Chapter 9
JFrame

1. Mousethe OS reports the click
2. EventQueuethe event enters the queue
3. EDTthe event dispatch thread takes it
4. ActionEventthe button creates an event
5. ListeneractionPerformed(e)

Swing Layout Managers

Goal: see that the position and size of the components inside a container (JPanel) are computed by the container's layout manager; watch the layout being recalculated when the window size changes, and see how a button click reaches the listener.

Layouts

  • FlowLayout (the default of JPanel): places the components left to right at their preferred sizes, wraps to the next row when a row is full, and centers each row; the gaps are 5 pixels.
  • BorderLayout (the default of a JFrame's content pane): NORTH and SOUTH get the full width and their preferred height; WEST and EAST get their preferred width and the remaining height; CENTER takes everything that is left. Each region holds a single component.
  • GridLayout(rows, columns, 5, 5): all cells are the same size; if the number of rows is greater than 0, the number of columns is computed from the number of components. The components fill their cells.
  • BoxLayout: puts the components one after another in a single column (Y) or a single row (X). Buttons stretch at most to their preferred size; they are aligned to the left on the Y axis and centered vertically on the X axis. What does not fit is cut off.

Events

A click first enters the event queue (EventQueue); the event dispatch thread (EDT) passes it to the button, the button creates an ActionEvent and calls the actionPerformed(e) method of every listener registered with addActionListener. If no listener is registered, the event is created but no code runs.

How to use it

  1. Choose a layout and add buttons with Add / Remove; choose the region for BorderLayout, and the rows and columns for GridLayout.
  2. Change the size of the content with the W and H sliders; the layout is recalculated instantly.
  3. Click a button in the window: the strip at the bottom shows the path of the event step by step.
  4. Test yourself: predict the result of the layout for a new size.

The preferred size of the buttons is computed here simply from the text length (26 + 8 × number of letters pixels wide, 26 pixels high). With the same preferred sizes, the positions computed by the real Java 8 FlowLayout, BorderLayout, GridLayout and BoxLayout classes came out exactly the same as this page's calculation for 345 different sizes and component counts.

Related slides: Chapter 9 · Graphics and User Interfaces (Layout Managers, BorderLayout, The JButton Class, ActionListener).