Concepts / Java Swing Components and Layouts

Java Swing Components and Layouts

GridLayout arranges components in a grid, and the add-call order determines their positions.

  • Programming

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?

  • Row 1, column 1

  • Row 1, column 2

  • Row 2, column 1

  • Row 2, column 2

Reveal answer
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.

Demo codeContent paneEvent listenersUser1. add six components to GridLayout2. register ChangeListener on 2 sliders3. register ActionListener on 3 buttons4. show window5. drag slider or click button
In what order are the six components created, added to the container, and wired to their listeners, and which step happens before the window is shown?

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.

Component 1Row 1, column 1Component 2Row 1, column 2Component 3Row 1, column 3Component 4Row 2, column 1Component 5Row 2, column 2Component 6Row 2, column 3
If six components are added to a 2 row by 3 column GridLayout in sequence, which cell does each one occupy?
Worked example

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?

  1. 1
    Count the cells

    A 2 by 3 grid has 6 cells, so there is room for all five components.

  2. 2
    Fill 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.

  3. 3
    Continue 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.

  4. 4
    Check the empty cell

    Row 2, column 3 has no component because only five were added.

Result

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.

PropertyWhat it controls on the rendered label
TextThe words the label displays
AlignmentWhere the text sits inside the label's area
BackgroundThe fill color behind the text
ForegroundThe color of the text itself
FontThe typeface, style, and size of the text
BorderThe outline drawn around the label

Properties of the JLabel configured in the demo, as named in the source pack.

java
Notes on the code
  • The constructor sets the initial text and centers it horizontally.
  • setOpaque(true) makes the label paint its background, so the background color is visible.
  • setBackground and setForeground set the fill and text colors.
  • setFont changes the typeface, style, and size.
  • setBorder draws 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.

UserJButtonActionListenerJLabel1. clicks2. notifies registered listener3. actionPerformed updates display
When the user clicks the button, how does the click travel from the button to the actionPerformed method, and what must be registered beforehand?

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.

Worked example

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?

  1. 1
    Setup is complete

    The label, buttons, and sliders were created and added to the GridLayout, and listeners were registered before the window was shown.

  2. 2
    Slider changes

    Dragging the slider to 70 triggers the ChangeListener, whose handler reads 70 and sets the label text to Value: 70.

  3. 3
    Button clicked

    Clicking Bold triggers the ActionListener, whose handler sets the label font to bold.

  4. 4
    Final display

    The label now reads Value: 70 in bold, because both events updated the same label.

Result

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 like

    A button shows up in the middle of the grid and the programmer rewrites the button's code.

    Why it fails

    The 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 instead

    Check the order of add calls first, then check the component's own setup.

  • Common mistake

    Forgetting to register a listener

    What it looks like

    A slider is created and added, but addChangeListener is never called, so dragging it does nothing.

    Why it fails

    A component does not send events to your code unless a listener is registered on it.

    Do this instead

    Register 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 like

    setBackground is called on a label, but the label still looks transparent.

    Why it fails

    The background of a label is painted only when the label is opaque, so the color does not show otherwise.

    Do this instead

    Call setOpaque(true) on the label before expecting setBackground to be visible.

Practice: Predict the Grid

MEDIUM

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

  • GridLayout places components into a grid, and the order of add calls determines which cell each component occupies.
  • A JLabel is configured through method calls for text, alignment, background, foreground, font, and border, and its background only shows when it is opaque.
  • A ChangeListener registered on a JSlider receives value changes in its stateChanged method, and an ActionListener registered on a JButton runs actionPerformed on 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.