Java Swing Components and Layouts
GridLayout arranges components in a grid, and the add-call order determines their positions.
A Window Built From Parts
A Swing window is not one object. It is a container that holds smaller parts: labels that show text, buttons that respond to clicks, and sliders that let the user choose a value. SliderAndButtonDemo is a small application that brings these ideas together. It uses one JLabel, three JButtons, and two JSliders, and it places all six components in a GridLayout. The sliders and buttons are connected to listeners, so the program can respond when the user changes them.
What do you think happens?
A container uses a GridLayout with 2 columns. Components A, B, and C are added to it in that order. Which cell holds C?
Reveal answer
Row 2, column 1
The source pack states that the add-call order determines positions in a GridLayout. Components fill the grid in order, so A takes row 1 column 1, B takes row 1 column 2, and C wraps to the start of row 2, column 1.
Tracing the Six Components
Before looking at how each component behaves, it helps to name the six parts of the demo and follow each one through its life. There are three kinds of work the program does with them. First, it creates each component as an object. Second, it adds each component to the container, which is what gives GridLayout the sequence it uses for the cells. Third, it registers listeners on the components that need to respond to the user. The window is shown only after this setup is complete.
Read the diagram as a timeline. Steps one through three are setup and happen before the window appears. Step four makes the window visible. Step five is the only step that depends on the user, and it happens after everything above is in place. The source pack does not give a line-by-line listing of the demo's creation order, so treat the sequence above as the general pattern a Swing program follows: create, add, register, then show.
How GridLayout Maps Insertion Order to Cells
GridLayout arranges components in a grid. You give it a number of rows and columns, and then you add components to the container. The add-call order determines which cell each component occupies. The first component added goes into the first cell, the next component goes into the next cell, and so on through the grid. This is why the order of add calls is a central part of debugging a layout. If a component appears in an unexpected place, the question to ask is whether the component itself is wrong or whether it was added at a different point in the sequence.
Predicting a Layout Before Running It
A 2 row by 3 column GridLayout receives components in the order Save, Load, Quit, Help, Undo. Where does each one appear?
- 1Count the cells
A 2 by 3 grid has 6 cells, so there is room for all five components.
- 2Fill row 1 first
Save is the first add call, so it goes to row 1, column 1. Load goes to row 1, column 2. Quit goes to row 1, column 3.
- 3Continue into row 2
Help is the fourth add call, so it goes to row 2, column 1. Undo is the fifth, so it goes to row 2, column 2.
- 4Check the empty cell
Row 2, column 3 has no component because only five were added.
Row 1 holds Save, Load, Quit. Row 2 holds Help and Undo, with the last cell empty.
Configuring the Central JLabel
The demo treats the JLabel as the central display component. Its job is to show text, and the demo configures several of its visual properties: text, alignment, background color, foreground color, font, and border. Each of these is set by a method call on the label object after it is created. The table below names the property and its visual effect.
| Property | What it controls on the rendered label |
|---|---|
| Text | The words the label displays |
| Alignment | Where the text sits inside the label's area |
| Background | The fill color behind the text |
| Foreground | The color of the text itself |
| Font | The typeface, style, and size of the text |
| Border | The outline drawn around the label |
Properties of the JLabel configured in the demo, as named in the source pack.
- The constructor sets the initial text and centers it horizontally.
setOpaque(true)makes the label paint its background, so the background color is visible.setBackgroundandsetForegroundset the fill and text colors.setFontchanges the typeface, style, and size.setBorderdraws an outline around the label.
Connecting Sliders and Buttons to Listeners
A listener is an object that your code registers on a component so that it is notified when something happens. The demo uses two kinds: a ChangeListener for the two sliders and an ActionListener for the three buttons. Registration is the step that connects the component to your code. Without it, moving the slider or clicking the button produces no response from the program.
Following One User Action Through the Program
Now combine the pieces. Suppose the user drags a slider and then clicks a button. The slider's change reaches its ChangeListener, the handler reads the new value, and the label is updated. The button click reaches its ActionListener, and the handler changes the label's font. Both events act on the same JLabel, which is why the label is described as the central display component. Each component stays responsible for its own event, while the label is the shared place where results appear.
Tracing a Slider Move Followed by a Button Click
The window is open and the label reads Value: 50 in plain font. The user drags a slider to 70, then clicks the Bold button. What does the user see at each step?
- 1Setup is complete
The label, buttons, and sliders were created and added to the
GridLayout, and listeners were registered before the window was shown. - 2Slider changes
Dragging the slider to 70 triggers the
ChangeListener, whose handler reads 70 and sets the label text to Value: 70. - 3Button clicked
Clicking Bold triggers the
ActionListener, whose handler sets the label font to bold. - 4Final display
The label now reads Value: 70 in bold, because both events updated the same label.
The label shows Value: 70 in bold text.
Mistakes Beginners Make With Layouts and Listeners
Common mistake Assuming the component is wrong when it appears in the wrong cell
What it looks likeA button shows up in the middle of the grid and the programmer rewrites the button's code.
Why it failsThe source pack notes that the add-call order determines positions in the
GridLayout, so the placement problem may come from the sequence of add calls rather than the component.Do this insteadCheck the order of add calls first, then check the component's own setup.
Common mistake Forgetting to register a listener
What it looks likeA slider is created and added, but addChangeListener is never called, so dragging it does nothing.
Why it failsA component does not send events to your code unless a listener is registered on it.
Do this insteadRegister a ChangeListener on each slider and an ActionListener on each button during setup.
Common mistake Expecting a label background color to appear without opaque painting
What it looks likesetBackground is called on a label, but the label still looks transparent.
Why it failsThe background of a label is painted only when the label is opaque, so the color does not show otherwise.
Do this insteadCall setOpaque(true) on the label before expecting setBackground to be visible.
Practice: Predict the Grid
A container uses a GridLayout with 3 rows and 2 columns. Components are added in this order: Slider, Label, Button 1, Button 2, Button 3, Button 4. For each component, name its row and column. Then explain what would change if the Label were added first instead of second.
Hints
- Fill row 1 left to right, then move to row 2, following the add-call order.
- The grid has 6 cells, so all six components fit with no empty cell.
- Moving the Label earlier shifts every component after it by one cell.
Key Takeaways
GridLayoutplaces components into a grid, and the order of add calls determines which cell each component occupies.- A
JLabelis configured through method calls for text, alignment, background, foreground, font, and border, and its background only shows when it is opaque. - A
ChangeListenerregistered on aJSliderreceives value changes in itsstateChangedmethod, and anActionListenerregistered on aJButtonrunsactionPerformedon each click. - SliderAndButtonDemo follows a clear sequence: components are created, added to the container, wired to listeners, and then shown, with user events happening last.