Swing Layout Managers and MVC: FlowLayout, BorderLayout and GridLayout
How Swing components are built and arranged: the model-view-controller design behind every component, button models and UI delegates, pluggable look and feel, and the three basic layout managers (flow, border and grid), combined with nested panels.
kvi5hnuCode Sprout team member12 min readOn this page
The previous part used buttons and painted components. This part tours the standard Swing components (text fields, check boxes, menus, dialogs) and the tools for arranging them. Two ideas run through all of it. First, every Swing component is built from separate pieces for its data, its appearance and its behavior, following the model-view-controller pattern; knowing this makes the more advanced components in Part 12 much easier. Second, you rarely position components by pixel: layout managers place and size them, so the window adapts to fonts, languages and resizing.
Model, view, controller
Every user interface component has three aspects:
- its content, such as whether a button is pressed or the text in a text field;
- its appearance: colors, size, the way it is drawn in a given state;
- its behavior: how it reacts to mouse clicks and keys.
Even a button combines these in subtle ways: it looks different when pressed, the press depends on mouse events, and the drawing depends on the look and feel. Swing separates them following the model-view-controller (MVC) pattern:
- the model stores the content and has no user interface at all;
- the view draws the content, possibly only part of it;
- the controller handles user input and decides whether it changes the model or only the view.

A text field shows the idea well. The model holds the complete string; the view displays the portion that fits. Typing a character makes the controller insert it into the model, which notifies its views, which repaint. Pressing an arrow key may only scroll the view; the model never hears about it. One model can have several views: an HTML editor might show rendered and source views of the same document, both updating as either is edited.
(The word "model" can mislead: it is not a simplified replica, as in a model airplane. Think instead of an artist's model, the real subject, and the view as one artist's painting of it.)
How Swing applies MVC
For most components, the model is an interface whose name ends in Model: ButtonModel, ListModel, TableModel, TreeModel, and for text, Document. JButton uses a DefaultButtonModel, whose properties describe the button's state:
| Property | Meaning |
|---|---|
actionCommand | the action command string |
mnemonic | the keyboard mnemonic |
armed | pressed, and the mouse is still over the button |
enabled | the button can be used |
pressed | pressed, and the mouse button not yet released |
rollover | the mouse is over the button |
selected | toggled on (check boxes, radio buttons) |
Note what is missing: the label and the icon. Those are view data stored in the JButton itself, so you cannot tell from a model what is written on the button. (Article 95 shows where this causes inconvenience with radio buttons.) The same model class serves push buttons and menu items; toggle buttons, check boxes and radio buttons use the subclass JToggleButton.ToggleButtonModel.
Swing merges view and controller into one UI delegate per component, a class whose name ends in UI. In the default "Metal" look and feel, a button's delegate is a MetalButtonUI, which paints the button and installs a listener that turns mouse and key events into model changes. So a JButton is really a wrapper: a JComponent holding a model, some view data (text, icons), and a UI delegate. Day to day you call methods on the JButton, which forwards to its model. You use models directly when it pays off: to share data between components, as the demo does with one Document behind a text field and a text area, or for lists, tables and trees, where your own model can supply data without copying it.
Pluggable look and feel
Because drawing lives in the UI delegates, an application can change its entire appearance by switching delegate sets, called look and feels:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // imitate the OS
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); // a modern cross-platform one
Call setLookAndFeel before creating components; to switch later, call SwingUtilities.updateComponentTreeUI(frame) afterwards. The JDK includes Metal (the default), Nimbus, a system look and feel per platform (Windows, macOS "Aqua", GTK on Linux) and the legacy Motif. Popular third-party ones include FlatLaf, which offers light and dark themes in the style of current desktop applications. UIManager.getInstalledLookAndFeels() lists the available ones.
Layout managers
Components are placed in containers. A container's layout manager decides the position and size of each child. Swing programmers rarely compute coordinates themselves, for good reasons: text widths depend on the font and language, users resize windows, and high-DPI screens scale everything.
Every component class extends Component, and containers extend Container, so containers can be nested in other containers. The hierarchy has two oddities: top-level windows such as JFrame are containers but cannot be put inside other containers, and JComponent extends Container, so technically you can add components to a JButton (they would not be shown properly).
Each container has a default layout manager: a JPanel uses FlowLayout, the content pane of a JFrame uses BorderLayout. Change it with setLayout, or pass it to the JPanel constructor:
var panel = new JPanel(new GridLayout(4, 4));
panel.add(component); // the layout manager decides where it goes
frame.add(component, BorderLayout.SOUTH); // with a placement constraint
How does a layout manager decide sizes? Each component reports a preferred size (from its text, icon and look and feel, or from getPreferredSize()/setPreferredSize), as well as a minimum and maximum size. The layout manager combines them according to its rules and also computes the container's own preferred size, which is what pack() uses.
FlowLayout
A flow layout puts components in a row at their preferred sizes, starting a new row when the current one is full, like words in a paragraph. Each row is centered by default. The constructor takes the alignment (CENTER, LEFT, RIGHT, or the orientation-aware LEADING and TRAILING) and optional horizontal and vertical gaps (5 pixels by default):
var panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
When the user resizes the window, components move between rows but keep their size. Flow layouts suit rows of buttons and toolbars; for forms they are too unpredictable.
BorderLayout
A border layout has five regions: NORTH, SOUTH, EAST, WEST and CENTER. Edge components get their preferred thickness (height for north and south, width for east and west) and are stretched along the edge; the center gets everything left over. When the window grows, only the center grows. Not every region needs to be used, and each region holds at most one component: adding a second makes the layout use only the new one, but the old component stays in the container (call remove to really get rid of it).
frame.add(new JScrollPane(textArea)); // CENTER is the default
frame.add(statusBar, BorderLayout.SOUTH);
The orientation-aware names PAGE_START, PAGE_END, LINE_START and LINE_END swap east and west automatically for right-to-left languages. The constants are strings ("South"), but use the constants; a misspelled literal compiles and fails at run time.
Because a border layout stretches its components, adding a button directly to SOUTH gives you a button as wide as the window, and a second button would replace it. The fix is the most important layout technique of all: nest panels. Put the buttons into a JPanel (flow layout keeps them at their natural size, centered) and put the panel into SOUTH:
var buttons = new JPanel();
buttons.add(okButton);
buttons.add(cancelButton);
frame.add(buttons, BorderLayout.SOUTH);
The demo shows both versions side by side.
GridLayout
A grid layout arranges components in rows and columns of identical cells, filling row by row in the order you add them. All cells have the size of the largest preferred size, and all grow and shrink together:
var keys = new JPanel(new GridLayout(4, 4, 4, 4)); // rows, columns, hgap, vgap
Either the rows or the columns (not both) may be 0, meaning "as many as needed". Complete windows are rarely so regular, but small grids are handy inside other layouts, for example new GridLayout(1, 0, 5, 0) for a row of equal-width buttons, or a calculator keypad:
import java.awt.*;
import java.math.BigDecimal;
import java.math.MathContext;
import javax.swing.*;
public class Calculator {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var frame = new JFrame("Calculator");
frame.add(new CalculatorPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
/** BorderLayout: display in NORTH, a 4 x 4 GridLayout of keys in CENTER. */
class CalculatorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final JTextField display = new JTextField("0");
private BigDecimal accumulator = BigDecimal.ZERO;
private String pendingOp = "=";
private boolean startNewNumber = true;
CalculatorPanel() {
super(new BorderLayout(4, 4));
setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setFont(display.getFont().deriveFont(20f));
add(display, BorderLayout.NORTH);
var keys = new JPanel(new GridLayout(4, 4, 4, 4));
for (String key : new String[] {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"}) {
var button = new JButton(key);
button.addActionListener(_ -> press(key));
keys.add(button);
}
add(keys, BorderLayout.CENTER);
}
private void press(String key) {
if (Character.isDigit(key.charAt(0)) || key.equals(".")) {
String current = startNewNumber ? "" : display.getText();
if (key.equals(".") && current.contains(".")) return;
display.setText(current.isEmpty() && key.equals(".") ? "0." : current + key);
startNewNumber = false;
} else {
BigDecimal value = new BigDecimal(display.getText());
try {
accumulator = switch (pendingOp) {
case "+" -> accumulator.add(value);
case "-" -> accumulator.subtract(value);
case "*" -> accumulator.multiply(value);
case "/" -> accumulator.divide(value, MathContext.DECIMAL64);
default -> value;
};
display.setText(accumulator.stripTrailingZeros().toPlainString());
} catch (ArithmeticException e) {
display.setText("Error");
accumulator = BigDecimal.ZERO;
}
pendingOp = key;
startNewNumber = true;
}
}
}
Beyond the basics
Real forms need more control than these three managers offer. Article 97 covers GridBagLayout and writing your own layout manager. Other options in the JDK are BoxLayout (a single row or column with glue and struts), GroupLayout (designed for GUI builders), and SpringLayout; the third-party MigLayout is a popular, concise alternative. GUI builders in IDEs generate layout code, but you will still need to read and adjust it.
Two practical rules:
- If you add or remove components after the window is visible, call
revalidate()on the container (andrepaint()if needed) so the layout is recomputed. - Avoid absolute positioning (
setLayout(null)withsetBounds). It breaks as soon as fonts, languages or screen scaling differ from the developer's machine.
The program
The demo uses fixed-size placeholder components instead of real buttons, so that the results are the same everywhere (real button sizes depend on fonts). It lays out containers at given sizes and prints them one character per pixel, each component drawn with its letter. Before that, it looks inside a JButton: its model, its UI delegate, and the model state during a press; and it shares one Document between two text components.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Solution {
/** A stand-in component with a fixed preferred size, drawn as its letter. */
static class Block extends JComponent {
private static final long serialVersionUID = 1L;
final char letter;
Block(char letter, int w, int h) {
this.letter = letter;
setPreferredSize(new Dimension(w, h));
}
}
/** Lays out the container at the given size and prints one character per pixel. */
static void show(String title, Container c, int w, int h) {
c.setSize(w, h);
layoutTree(c);
char[][] grid = new char[h][w];
for (char[] row : grid) java.util.Arrays.fill(row, '.');
paintTree(c, 0, 0, grid);
System.out.println(title + " (" + w + " x " + h + ")");
for (char[] row : grid) System.out.println(" " + new String(row));
}
static void layoutTree(Container c) {
c.doLayout();
for (Component child : c.getComponents()) if (child instanceof Container k) layoutTree(k);
}
static void paintTree(Container c, int ox, int oy, char[][] grid) {
for (Component child : c.getComponents()) {
Rectangle r = child.getBounds();
if (child instanceof Block b) {
for (int y = r.y; y < r.y + r.height; y++)
for (int x = r.x; x < r.x + r.width; x++) {
int gx = ox + x, gy = oy + y;
if (gy >= 0 && gy < grid.length && gx >= 0 && gx < grid[0].length) grid[gy][gx] = b.letter;
}
} else if (child instanceof Container k) {
paintTree(k, ox + r.x, oy + r.y, grid);
}
}
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
EventQueue.invokeAndWait(Solution::run);
}
static void run() {
System.out.println("== Model, view and controller of a JButton ==");
var button = new JButton("Blue");
ButtonModel model = button.getModel();
System.out.println("model: " + model.getClass().getSimpleName() + ", UI delegate (view + controller): "
+ button.getUI().getClass().getSimpleName() + ", UI class ID: " + button.getUIClassID());
System.out.println("look and feel: " + UIManager.getLookAndFeel().getName());
model.setArmed(true);
model.setPressed(true);
System.out.println("pressed=" + model.isPressed() + " armed=" + model.isArmed() + " rollover=" + model.isRollover()
+ " selected=" + model.isSelected() + " enabled=" + model.isEnabled());
var fired = new int[1];
button.addActionListener(_ -> fired[0]++);
model.setPressed(false); // releasing an armed button fires the action
System.out.println("released while armed -> action events: " + fired[0]);
System.out.println("the model knows nothing about the label; button.getText() = " + button.getText());
System.out.println("check box and menu item models: " + new JCheckBox().getModel().getClass().getSimpleName()
+ " and " + new JMenuItem().getModel().getClass().getSimpleName());
System.out.println("\n== One model, two views ==");
var field = new JTextField(10);
var area = new JTextArea(3, 10);
area.setDocument(field.getDocument()); // share the model
field.setText("shared text");
System.out.println("text area shows: \"" + area.getText() + "\"");
try {
area.getDocument().insertString(0, ">> ", null);
} catch (BadLocationException e) {
throw new IllegalStateException(e);
}
System.out.println("after editing through the area, field shows: \"" + field.getText() + "\"");
System.out.println("\n== FlowLayout: preferred sizes, rows wrap, centered ==");
var flow = new JPanel(new FlowLayout(FlowLayout.CENTER, 2, 1)); // hgap 2, vgap 1
for (char ch : "ABCDEF".toCharArray()) flow.add(new Block(ch, 10, 2));
show("wide", flow, 72, 4);
show("narrow", flow, 40, 7);
flow.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 1));
show("narrow, LEFT aligned", flow, 40, 7);
System.out.println("\n== BorderLayout: edges get their preferred thickness, CENTER the rest ==");
var border = new JPanel(new BorderLayout(1, 0));
border.add(new Block('N', 5, 2), BorderLayout.NORTH);
border.add(new Block('S', 5, 2), BorderLayout.SOUTH);
border.add(new Block('W', 6, 5), BorderLayout.WEST);
border.add(new Block('E', 4, 5), BorderLayout.EAST);
border.add(new Block('C', 5, 5)); // no constraint means CENTER
show("small", border, 30, 9);
show("bigger: only the center grows", border, 44, 12);
System.out.println("\n== A button in SOUTH is stretched; a panel in SOUTH keeps buttons at preferred size ==");
var stretched = new JPanel(new BorderLayout());
stretched.add(new Block('C', 5, 5));
stretched.add(new Block('Y', 8, 2), BorderLayout.SOUTH);
show("button directly in SOUTH", stretched, 40, 7);
var nested = new JPanel(new BorderLayout());
nested.add(new Block('C', 5, 5));
var buttons = new JPanel(new FlowLayout(FlowLayout.CENTER, 2, 0));
for (char ch : "YBR".toCharArray()) buttons.add(new Block(ch, 8, 2));
nested.add(buttons, BorderLayout.SOUTH);
show("button panel in SOUTH", nested, 40, 7);
System.out.println("\n== GridLayout: equal cells, filled row by row ==");
var grid = new JPanel(new GridLayout(4, 4, 1, 0));
for (char ch : "789/456*123-0,=+".toCharArray()) grid.add(new Block(ch, 3, 1));
show("calculator keys", grid, 31, 4);
System.out.println("grid preferred size = " + grid.getPreferredSize().width + " x " + grid.getPreferredSize().height
+ " (4 columns of the widest cell + 3 gaps)");
var oneColumn = new JPanel(new GridLayout(0, 1)); // 0 rows: as many as needed
for (char ch : "XYZ".toCharArray()) oneColumn.add(new Block(ch, 6, 1));
show("GridLayout(0, 1)", oneColumn, 10, 3);
}
}
== Model, view and controller of a JButton ==
model: DefaultButtonModel, UI delegate (view + controller): MetalButtonUI, UI class ID: ButtonUI
look and feel: Metal
pressed=true armed=true rollover=false selected=false enabled=true
released while armed -> action events: 1
the model knows nothing about the label; button.getText() = Blue
check box and menu item models: ToggleButtonModel and DefaultButtonModel
== One model, two views ==
text area shows: "shared text"
after editing through the area, field shows: ">> shared text"
== FlowLayout: preferred sizes, rows wrap, centered ==
wide (72 x 4)
........................................................................
.AAAAAAAAAA..BBBBBBBBBB..CCCCCCCCCC..DDDDDDDDDD..EEEEEEEEEE..FFFFFFFFFF.
.AAAAAAAAAA..BBBBBBBBBB..CCCCCCCCCC..DDDDDDDDDD..EEEEEEEEEE..FFFFFFFFFF.
........................................................................
narrow (40 x 7)
........................................
...AAAAAAAAAA..BBBBBBBBBB..CCCCCCCCCC...
...AAAAAAAAAA..BBBBBBBBBB..CCCCCCCCCC...
........................................
...DDDDDDDDDD..EEEEEEEEEE..FFFFFFFFFF...
...DDDDDDDDDD..EEEEEEEEEE..FFFFFFFFFF...
........................................
narrow, LEFT aligned (40 x 7)
........................................
..AAAAAAAAAA..BBBBBBBBBB..CCCCCCCCCC....
..AAAAAAAAAA..BBBBBBBBBB..CCCCCCCCCC....
........................................
..DDDDDDDDDD..EEEEEEEEEE..FFFFFFFFFF....
..DDDDDDDDDD..EEEEEEEEEE..FFFFFFFFFF....
........................................
== BorderLayout: edges get their preferred thickness, CENTER the rest ==
small (30 x 9)
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
WWWWWW.CCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCC.EEEE
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
bigger: only the center grows (44 x 12)
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
WWWWWW.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.EEEE
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
== A button in SOUTH is stretched; a panel in SOUTH keeps buttons at preferred size ==
button directly in SOUTH (40 x 7)
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
button panel in SOUTH (40 x 7)
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
......YYYYYYYY..BBBBBBBB..RRRRRRRR......
......YYYYYYYY..BBBBBBBB..RRRRRRRR......
== GridLayout: equal cells, filled row by row ==
calculator keys (31 x 4)
7777777.8888888.9999999.///////
4444444.5555555.6666666.*******
1111111.2222222.3333333.-------
0000000.,,,,,,,.=======.+++++++
grid preferred size = 15 x 4 (4 columns of the widest cell + 3 gaps)
GridLayout(0, 1) (10 x 3)
XXXXXXXXXX
YYYYYYYYYY
ZZZZZZZZZZ
Points to notice:
- Releasing an armed button through its model fired an action event; the button's own UI delegate does exactly this when you release the mouse over the button.
- In the flow layout, shrinking the container moved D, E and F to a second row; the blocks kept their size. With
LEFTalignment, the rows start at the left gap instead of being centered. - In the border layout, growing the container from 30×9 to 44×12 enlarged only the center; the edges kept their thickness.
- The grid's preferred width, 15, is four cells of 3 pixels plus three 1-pixel gaps; at 31 pixels wide, the extra space was shared equally among the cells.
Common questions
Why does my component not appear after I add it?
After adding or removing components in a visible container, call revalidate() (to redo the layout) and repaint(). Before the window is shown, pack() or setVisible(true) lays it out.
Should I use setLayout(null) and absolute positions?
Avoid it. Fonts, languages, high-DPI scaling and window sizes all change component sizes, and absolute layouts break. Nest the standard managers, or use GridBagLayout, GroupLayout or MigLayout for forms.
Why are my components squeezed or not the size I set?
Most layout managers ignore setSize; they use the preferred, minimum and maximum sizes. Override getPreferredSize() or call setPreferredSize (sparingly), and choose a layout that respects it.
How do I switch to dark mode?
The JDK's own look-and-feels have no dark theme. FlatLaf provides FlatDarkLaf and FlatMacDarkLaf. Call setup() before creating components, or updateComponentTreeUI to switch at run time.
What's the difference between validate, revalidate and repaint?
revalidate() marks a component as needing layout and schedules it on the EDT; validate() performs layout immediately (used on top-level windows); repaint() schedules painting without changing layout. After structural changes, call revalidate() then repaint().
API reference
| Class / method | Purpose |
|---|---|
AbstractButton.getModel(), ButtonModel.isPressed/isArmed/isRollover/isSelected/isEnabled | Button state. |
JComponent.getUI(), getUIClassID(), updateUI() | UI delegate. |
UIManager.setLookAndFeel, getSystemLookAndFeelClassName, getInstalledLookAndFeels, SwingUtilities.updateComponentTreeUI | Look and feel. |
JTextComponent.getDocument(), setDocument(doc) | Text model; share between components. |
Container.setLayout(manager), add(c), add(c, constraints), revalidate() | Layout. |
FlowLayout(align, hgap, vgap); LEFT, CENTER, RIGHT, LEADING, TRAILING | Flow layout. |
BorderLayout(hgap, vgap); NORTH, SOUTH, EAST, WEST, CENTER, PAGE_START, PAGE_END, LINE_START, LINE_END | Border layout. |
GridLayout(rows, cols, hgap, vgap) | Grid of equal cells; 0 for "any number". |
getPreferredSize, setPreferredSize, getMinimumSize, getMaximumSize | Size hints for layout managers. |
Summary
- Swing components follow MVC: a model (such as
ButtonModelorDocument) holds content, and a UI delegate combines view and controller. The component class ties them together and forwards most calls. - Share a model to show the same data in several components; replace the UI delegates wholesale by switching the look and feel.
- Layout managers position and size components from their preferred sizes.
JPaneldefaults toFlowLayout, a frame's content pane toBorderLayout. FlowLayoutkeeps preferred sizes and wraps rows;BorderLayoutstretches edges and gives the rest to the center;GridLayoutmakes all cells equal.- Build real layouts by nesting panels with different managers. Call
revalidate()after changing a visible container's children, and avoid absolute positioning.
Practice Questions
1. Where is a JButton's label stored, and why not in its ButtonModel?
The label (and icons) are view data stored in the JButton object itself. The model holds only the state needed to describe how the button behaves (pressed, armed, selected, enabled, rollover, mnemonic, action command). This keeps the model independent of any visual representation, so the same model class can serve buttons, check boxes and menu items. The downside is that, given only a model, you cannot find out what the button says.
2. You add three buttons with frame.add(button, BorderLayout.SOUTH), one after another. Only the last button appears, as wide as the window. Explain and fix.
Each border layout region holds one component, so after each add to SOUTH the layout uses only the newest button (the others stay in the container but aren't laid out), and the border layout stretches the remaining button across the whole width. Put the buttons into a JPanel (which uses a flow layout and keeps them at their preferred sizes) and add that panel to SOUTH.
3. What is the difference between new GridLayout(3, 0) and new GridLayout(0, 3)?
GridLayout(3, 0) fixes three rows and creates as many columns as needed; GridLayout(0, 3) fixes three columns and creates as many rows as needed. With nine components both give 3 × 3. With ten, the first gives 3 rows × 4 columns and the second 4 rows × 3 columns. In both cases the cells are filled row by row.
4. A program adds a new row of components to a panel when the user clicks "Add", but nothing appears until the window is resized. Why?
Adding a component to a container that is already displayed marks the layout as invalid but does not recompute it. The new component has no size until the next layout pass, which resizing triggers. Call panel.revalidate() (and panel.repaint() if components were removed) after changing the children.
5. Why is setLayout(null) with hand-placed setBounds calls considered bad practice?
Fixed pixel positions assume one font, one language and one screen scaling. On another platform or look and feel, text may be wider and get cut off; translated labels may be longer; users may resize the window and the components stay put; and high-DPI or accessibility settings change sizes. Layout managers compute positions from the actual preferred sizes, so the interface adapts.
Previous: The Java Preferences API: Storing User Settings
Next: Swing Text Components: Text Fields, Labels, Password Fields and Text Areas
Related reading

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.