Adding Actions to Buttons in Java GUI Programming
A JToolBar is created with new JToolBar() and placed in a container, such as along BorderLayout.NORTH, using an add call with a region name.
Predicting the Toolbar Before Reading Further
This article works from a real example rather than from a list of rules. The example is the constructor of a Swing application that draws with the mouse and offers a small toolbar at the top of the window. The toolbar holds three color choices, presented as radio buttons, followed by a separator and a clear button.
Before reading any explanation, try to form your own picture of the window. What will it look like, and in what order will its pieces appear? Make that prediction now, because the gap between what you expected and what the code actually does is where debugging begins.
The goal of this article is to connect each line of that constructor to one visible or structural result. Once you can do that, you can also find the exact line where a toolbar behaves differently from what you expected, which is the skill that matters most when a GUI does not look right.
Creating the Toolbar and Adding Its Items
A toolbar in Swing is created with new JToolBar(). Creating the object does not make it visible on its own. It becomes part of the window only when it is placed into a container, and the components it holds are added to it with add calls. Each add call contributes one item to the toolbar.
The toolbar in the source example holds, in order, three color radio buttons, a separator, and a clear button. The source excerpt describes this layout, and the important rule it demonstrates is that components appear on the toolbar in the order their add calls run. Swing does not reorder components for you, and nothing about a button's purpose changes its position.
- new
JToolBar()creates an empty toolbar object - Each add call places one component at the next position
addSeparatorwith a Dimension argument inserts a divider at the current position- The clear button is added last, so it is the final item
Where Each Toolbar Item Lands
Think of the toolbar as a row of numbered slots. Each add call fills the next free slot, moving from left to right. Changing the order of the add calls changes which component ends up in which slot, while the components themselves stay the same.
The diagram reads as the result of five add calls made in the order shown in the sketch. The clear button sits at the far right end because its add call runs last. If a later edit moved the clear button's add call above the color buttons, the clear button would move to the left end. The toolbar would not complain; it would simply show the new order.
Placing the Toolbar Along the Top Edge
A toolbar must be placed in a container to appear in a window. The source describes this placement as an add call that includes a region name, such as BorderLayout.NORTH. That region name tells the container where the toolbar should go. BorderLayout.NORTH places the toolbar along the top edge of the container, and the CENTER region is left for the main drawing area.
The toolbar itself does not decide where it goes. The container's layout manager makes that decision, based on the region name given in the add call. The same toolbar object placed under a different region name would appear somewhere else in the window.
Why Radio Buttons Need a Shared Group
The three color choices are radio buttons. Radio buttons are meant to offer mutually exclusive options: the user picks one color, and picking another should release the first. Placing buttons next to each other on a toolbar does not create this behavior. Swing does not provide it automatically, so the grouping must be declared.
In this example the grouping is declared with a ButtonGroup. The code creates one group object and passes that same group to each color button. The group, not the individual buttons, is responsible for the rule that only one choice can be selected at a time.
Each color button is created by a call to makeColorRadioButton. That helper takes the color, the shared group, and a boolean. The source excerpt does not show the body of this helper, so this article does not describe how it uses the boolean internally. The excerpt does show that the red call passes true, the green and blue calls pass false, and all three calls share the same group.
- The group is created once and reused by every color button
- The boolean argument differs between the red call and the other two calls
- The body of
makeColorRadioButtonis not shown in the source
The diagram shows that the group holds one current selection. Clicking green releases red, because the group allows only one of its buttons to be selected. The transitions shown are the logical behavior the group enforces; the excerpt itself describes the group's purpose rather than the internal mechanism.
Tracing the Constructor Line by Line
A useful way to read any Swing constructor is to walk through it one line at a time and write down, for each line, what has been created and where it now sits. The source recommends exactly this: trace the constructor line by line and compare each line's effect with what you expected. The first line that diverges from your expectation is the failure location.
Following the toolbar construction step by step
Starting from an empty window, determine what exists and where it is after each step of the toolbar setup, and identify which item sits at the far right of the toolbar when the constructor finishes.
- 1Create the toolbar
new
JToolBar()creates an empty toolbar. Nothing is visible yet, and the toolbar is not yet placed in the window. - 2Create the shared group
The ButtonGroup object is created once. It holds no buttons yet, but it is ready to receive them.
- 3Create and register the color buttons
Each
makeColorRadioButtoncall builds one radio button tied to the same group. Red is created with true, green and blue with false. The group now manages all three. - 4Add the color buttons to the toolbar
Each add call places its button at the next free slot, so red takes the leftmost position, then green, then blue.
- 5Add the separator
addSeparatorwith a Dimension argument appends a divider after the blue button. - 6Add the clear button
The clear button is added last, so it takes the rightmost slot.
- 7Place the toolbar in the window
The add call with
BorderLayout.NORTH positions the whole toolbar along the top edge of the container.
The clear button is at the far right end of the toolbar. The toolbar sits along the top edge, and the three color radio buttons form one mutually exclusive set.
What do you think happens?
Once the constructor finishes, which item sits at the far right end of the toolbar?
Reveal answer
The clear button.
The toolbar's contents follow the order of the add calls. The clear button's add call runs last, after the color buttons and the separator, so it occupies the rightmost position.
Mistakes When Reading Toolbar Code
Common mistake Assuming that buttons placed side by side on a toolbar are automatically mutually exclusive
What it looks likeThree radio buttons added to a toolbar with no shared group, where clicking one does not release the others
Why it failsSwing does not get this behavior just because the buttons sit next to each other. The grouping must be declared.
Do this insteadCreate one ButtonGroup and pass the same group to each radio button.
Common mistake Creating a new ButtonGroup for each radio button
What it looks likeEach color button receives its own fresh group object
Why it failsThe source uses one group object for all of the color buttons, because the group is what enforces the single-selection rule. Separate groups do not know about each other.
Do this insteadCreate the group once and pass that same object to every call that needs it.
Common mistake Expecting Swing to reorder toolbar items to match their visual importance
What it looks likeMoving the clear button to the left because it is a different kind of control
Why it failsComponents on a toolbar appear in the order their add calls run. Swing does not reorder them.
Do this insteadChange the order of the add calls if you want a different left-to-right arrangement.
Common mistake Reading the placement region as a property of the toolbar
What it looks likeBelieving the toolbar always appears at the top regardless of how it is added
Why it failsThe toolbar does not decide its location. The layout manager uses the region name given in the add call.
Do this insteadCheck the region name in the add call, such as BorderLayout.NORTH, to know where the toolbar will appear.
Common mistake Searching for a bug in the toolbar's appearance before checking the order of the add calls
Practicing a Toolbar Trace
Suppose a developer moves the separator's add call so that it runs before the green and blue buttons are added, while keeping the red button first. Using the trace method, describe the new left-to-right order of the toolbar and identify the line where the result first differs from the original layout.
Hints
- Write down the toolbar's contents after each add call, in order.
- Remember that each add call fills the next free slot from left to right.
- Compare your new sequence with the original one line by line to find the first difference.
Without running the code, sketch the window and list the toolbar's items from left to right after the constructor finishes, then explain in one sentence why the radio buttons behave as a single set.
Hints
- The answer for the layout comes from the order of the add calls.
- The answer for the radio buttons comes from the shared ButtonGroup.
Key Takeaways
- A toolbar is created with new
JToolBar(), gets its items from add calls, and is placed in a container with a region name such asBorderLayout.NORTH. - Components on a toolbar appear in the order their add calls run, and Swing does not reorder them for you.
- Radio buttons are mutually exclusive only when they share a ButtonGroup, which is the object that enforces the single-selection rule.
- To find an unexpected toolbar result, trace the constructor line by line and stop at the first line whose effect differs from what you expected.