Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders
Letting users choose instead of type: check boxes, radio buttons in button groups, borders and titled panels, generic combo boxes and their models, sliders with ticks and labels, plus spinners and lists.
kvi5hnuCode Sprout team member12 min readOn this page
Often the user should not type at all but pick from a fixed set of possibilities. Choices tell users what is possible and save you from validating free text. Swing offers a component for each kind of choice; the diagram is a quick guide. This article covers check boxes, radio buttons, borders (to group them visually), combo boxes and sliders, and then briefly two more that complete the set: spinners and lists.

Check boxes
A check box collects a yes/no answer. It comes with its own label, so it needs no separate JLabel. The user toggles it by clicking it or by pressing the space bar while it has focus.
var bold = new JCheckBox("Bold");
var italic = new JCheckBox("Italic", true); // initially checked
isSelected() reads the state and setSelected(b) sets it. A click generates an action event. When several check boxes together determine one result, it is natural to give them a shared listener that reads all of them:
ActionListener listener = _ -> {
int style = Font.PLAIN;
if (bold.isSelected()) style |= Font.BOLD;
if (italic.isSelected()) style |= Font.ITALIC;
label.setFont(label.getFont().deriveFont(style));
};
bold.addActionListener(listener);
italic.addActionListener(listener);
Note the difference between the two kinds of events a check box can fire. Action events fire when the user clicks (or the program calls doClick). Item events (addItemListener) fire whenever the selected state changes, including through setSelected. The demo shows that setSelected(true) leaves an action listener uninformed. Use action listeners to react to user choices, and item listeners when you must track the state no matter who changes it.
Radio buttons
Radio buttons offer mutually exclusive options: selecting one clears the previously selected one, like the station buttons of an old car radio. Create a ButtonGroup and add the buttons to it:
var group = new ButtonGroup();
var small = new JRadioButton("Small", false);
var medium = new JRadioButton("Medium", true); // the initially selected one
group.add(small);
group.add(medium);
The group only handles the exclusive behavior. It is not a component, so the buttons still need to be added to a panel for layout. Radio buttons look different from check boxes (round with a dot rather than square with a check mark), which tells users that only one can be on.
Radio buttons also fire action events. Here a separate listener per button is often clearest, because each one knows its value:
void addSizeButton(String name, int size) {
var button = new JRadioButton(name, size == DEFAULT_SIZE);
button.addActionListener(_ -> label.setFont(label.getFont().deriveFont((float) size)));
group.add(button);
buttonPanel.add(button);
}
Which button is selected?
ButtonGroup.getSelection() seems like the answer, but it returns the ButtonModel of the selected button, not the button. As Article 93 explained, the model knows nothing about the label, and its action command is null unless you set one. The demo shows the workaround: call setActionCommand on each button (which also sets it on the model), and then group.getSelection().getActionCommand() identifies the choice. Alternatively, keep the buttons in a list or map and test isSelected(), or simply remember the value in the button's listener.
Two more details:
- Once a button in a group is selected, the user cannot unselect all of them. If "none" is a valid answer, add a "None" button, or call
group.clearSelection()from code. - When the user picks a new button, the old one fires an item event
DESELECTEDand the new oneSELECTED.
Borders
With several groups of options in one window, borders show which controls belong together. Any JComponent can have a border; most often you put a border around a panel full of buttons. Borders are created by static methods of BorderFactory:
| Factory method | Effect |
|---|---|
createEmptyBorder(top, left, bottom, right) | blank space; the most used border of all, for padding |
createLineBorder(color, thickness) | a plain line |
createEtchedBorder() | a thin groove with a 3D effect (EtchedBorder.LOWERED or RAISED) |
createLoweredBevelBorder(), createRaisedBevelBorder() | a sunken or raised surface |
createMatteBorder(top, left, bottom, right, color or icon) | edges of different thickness, filled with a color or a tiled icon |
createTitledBorder(border, title) | adds a title to another border |
createCompoundBorder(outside, inside) | combines two borders |
Install a border with setBorder:
var panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Size"));
The titled border has further options: the title's justification (LEFT, CENTER, RIGHT, LEADING, TRAILING), its position relative to the line (ABOVE_TOP, TOP, BELOW_TOP, and the same for the bottom), a font and a color. Since Java 7, BorderFactory also has createRaisedSoftBevelBorder()/createLoweredSoftBevelBorder() (a bevel with softened corners), createLineBorder(color, thickness, true) for rounded corners, and createDashedBorder/createStrokeBorder for dashed or custom-stroke lines.
A border takes up space inside the component, reported by getBorderInsets. The demo prints the insets of each kind: a compound border's insets are the sum of its parts. A common pattern adds padding inside a line: createCompoundBorder(createLineBorder(...), createEmptyBorder(6, 6, 6, 6)). Modern designs use fewer decorative borders than the bevels of the 1990s; empty borders for spacing and titled borders for grouping cover most needs.
Combo boxes
With more than a handful of options, radio buttons take too much space. A combo box shows only the current choice; clicking it drops down the list. If the combo box is editable, the user can also type a value that is not in the list, which combines a text field with a list of suggestions; hence the name.
JComboBox is generic in the type of its items:
var faces = new JComboBox<String>();
faces.addItem("Serif");
faces.addItem("SansSerif");
faces.insertItemAt("Monospaced", 0); // at the beginning
faces.removeItem("Monospaced");
faces.removeItemAt(0);
faces.removeAllItems();
You can also pass an array or a Vector to the constructor. Items can be any objects; the combo box displays their toString(), so a record with a suitable toString lets the user pick a domain object directly, as the demo's Unit record does. (For more control over the display, install a ListCellRenderer; renderers are covered with tables in Part 12.)
When the user selects an item, the combo box fires an action event. Read the selection like this:
String face = faces.getItemAt(faces.getSelectedIndex()); // typed result
The older getSelectedItem() returns Object and needs a cast. It is still needed for editable combo boxes, because a typed value is not in the list: its index is -1, as the demo shows, and the item comes from the editor (a String for the default editor). Editing never changes the list of choices.
Two practical notes. Adding the first item to an empty combo box selects it and fires an action event, so add listeners after filling the box, or be prepared for that event. And adding many items one by one is slow, because each call notifies the view. Fill a DefaultComboBoxModel first (its addAll method takes a collection) and install it with setModel or the constructor. That model is the "M" in MVC for combo boxes; your own ComboBoxModel implementation can supply items computed on demand.
Sliders
A slider chooses a value from a continuous range by dragging a knob:
var slider = new JSlider(min, max, initialValue);
var vertical = new JSlider(SwingConstants.VERTICAL, min, max, initialValue);
Without arguments, the range is 0 to 100 starting at 50. When the value changes, the slider sends a ChangeEvent to its ChangeListeners:
slider.addChangeListener(event -> {
var source = (JSlider) event.getSource();
valueField.setText("" + source.getValue());
});
While the user drags, change events arrive continuously, and getValueIsAdjusting() returns true. If the reaction is expensive (rerunning a query, resizing a large image), skip events while the value is adjusting and act on the final one. Values outside the range are clamped, and setting the current value again fires nothing.
Decorations are switched on separately:
slider.setMajorTickSpacing(20); // in slider units, not pixels
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true); // without this, no ticks are drawn
slider.setPaintLabels(true); // labels 0, 20, 40, ... at the major ticks
If ticks or labels do not appear, check the setPaint... calls first. For custom labels, put components (usually JLabels with text or icons) into a Hashtable<Integer, JComponent> keyed by slider value and call setLabelTable. Other options: setSnapToTicks(true) moves the knob to the nearest tick after dragging (but listeners still see the in-between values during the drag), setPaintTrack(false) hides the track, and setInverted(true) reverses the direction.
A slider's model is a BoundedRangeModel, the same model used by scroll bars and progress bars. The demo connects a slider and a progress bar through one model, so moving the slider moves the bar without any listener.
Spinners and lists
Two more choice components deserve a mention.
A JSpinner is a small text field with up and down arrows. Its model determines what it steps through: SpinnerNumberModel(value, min, max, step) for numbers, SpinnerListModel(list) for a sequence of values, and SpinnerDateModel for dates. Unlike a slider, it lets the user enter an exact value, and it takes little space. getNextValue() returns null at the end of the range.
A JList shows several items at once and allows multiple selections (with Ctrl or Shift clicks), depending on setSelectionMode. getSelectedValuesList() returns the selection. Put a list into a JScrollPane; setVisibleRowCount sets how many rows it shows (8 by default). A ListSelectionListener reports selection changes. Like combo boxes, lists take a ListModel, and DefaultListModel is the mutable standard implementation.
A font chooser
This program combines the components of the article. A combo box selects the face, check boxes the style, and a slider the size; radio buttons in a titled panel offer size presets that move the slider. Every control triggers the same updateSample method, which reads all the controls.
import java.awt.*;
import javax.swing.*;
public final class FontChooserFrame extends JFrame {
private static final long serialVersionUID = 1L;
private final JLabel sample = new JLabel("Pack my box with five dozen liquor jugs.",
SwingConstants.CENTER);
private final JComboBox<String> faceBox = new JComboBox<>(
new String[] {Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, Font.DIALOG});
private final JCheckBox bold = new JCheckBox("Bold");
private final JCheckBox italic = new JCheckBox("Italic");
private final JSlider sizeSlider = new JSlider(8, 48, 24);
public FontChooserFrame() {
super("Font chooser");
sample.setPreferredSize(new Dimension(520, 120));
add(sample, BorderLayout.CENTER);
// presets: radio buttons that move the slider
var presets = new JPanel(new GridLayout(0, 1));
presets.setBorder(BorderFactory.createTitledBorder("Preset"));
var group = new ButtonGroup();
addPreset(presets, group, "Small", 10);
addPreset(presets, group, "Normal", 24);
addPreset(presets, group, "Huge", 48);
var styles = new JPanel(new GridLayout(0, 1));
styles.setBorder(BorderFactory.createTitledBorder("Style"));
styles.add(bold);
styles.add(italic);
sizeSlider.setMajorTickSpacing(10);
sizeSlider.setMinorTickSpacing(2);
sizeSlider.setPaintTicks(true);
sizeSlider.setPaintLabels(true);
var sizePanel = new JPanel(new BorderLayout());
sizePanel.setBorder(BorderFactory.createTitledBorder("Size"));
sizePanel.add(sizeSlider);
var controls = new JPanel();
controls.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
controls.add(faceBox);
controls.add(styles);
controls.add(presets);
controls.add(sizePanel);
add(controls, BorderLayout.SOUTH);
faceBox.addActionListener(_ -> updateSample());
bold.addActionListener(_ -> updateSample());
italic.addActionListener(_ -> updateSample());
sizeSlider.addChangeListener(_ -> updateSample());
updateSample();
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private void addPreset(JPanel panel, ButtonGroup group, String name, int size) {
var button = new JRadioButton(name, size == sizeSlider.getValue());
button.addActionListener(_ -> sizeSlider.setValue(size));
group.add(button);
panel.add(button);
}
private void updateSample() {
int style = (bold.isSelected() ? Font.BOLD : 0) | (italic.isSelected() ? Font.ITALIC : 0);
String face = faceBox.getItemAt(faceBox.getSelectedIndex());
sample.setFont(new Font(face, style, sizeSlider.getValue()));
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new FontChooserFrame().setVisible(true));
}
}
The program
The demo drives the choice components from code. doClick(0) simulates a user click without the default visual delay of 68 milliseconds; the other methods change state directly, the way your own code would.
import java.awt.Color;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
import javax.swing.border.*;
public class Solution {
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
SwingUtilities.invokeAndWait(Solution::run);
}
static void run() {
checkBoxes();
radioButtons();
borders();
comboBoxes();
sliders();
spinnersAndLists();
}
static String styleName(int style) {
return switch (style) {
case Font.PLAIN -> "PLAIN";
case Font.BOLD -> "BOLD";
case Font.ITALIC -> "ITALIC";
default -> "BOLD+ITALIC";
};
}
static void checkBoxes() {
System.out.println("== Check boxes: one listener reads both states ==");
var bold = new JCheckBox("Bold", true);
var italic = new JCheckBox("Italic");
int[] style = {Font.BOLD};
ActionListener listener = _ -> {
int mode = Font.PLAIN;
if (bold.isSelected()) mode |= Font.BOLD;
if (italic.isSelected()) mode |= Font.ITALIC;
style[0] = mode;
System.out.println(" style -> " + styleName(mode));
};
bold.addActionListener(listener);
italic.addActionListener(listener);
System.out.println("start: bold=" + bold.isSelected() + ", italic=" + italic.isSelected());
italic.doClick(0);
bold.doClick(0);
italic.doClick(0);
System.out.println("setSelected(true) fires no action event:");
bold.setSelected(true);
System.out.println(" style still " + styleName(style[0]) + ", but bold is now " + bold.isSelected());
}
static void radioButtons() {
System.out.println();
System.out.println("== Radio buttons in a ButtonGroup ==");
var group = new ButtonGroup();
String[] names = {"Small", "Medium", "Large", "Extra large"};
int[] sizes = {8, 12, 18, 36};
int[] current = {12};
List<JRadioButton> buttons = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
int size = sizes[i];
var button = new JRadioButton(names[i], size == 12);
button.addActionListener(_ -> current[0] = size); // each button knows its size
group.add(button);
buttons.add(button);
}
JRadioButton large = buttons.get(2);
large.addItemListener(e -> System.out.println(" item event on Large: "
+ (e.getStateChange() == ItemEvent.SELECTED ? "SELECTED" : "DESELECTED")));
large.doClick(0);
System.out.println("size = " + current[0] + ", selected: " + selectedNames(buttons));
buttons.get(0).doClick(0);
System.out.println("size = " + current[0] + ", selected: " + selectedNames(buttons));
System.out.println("group.getSelection().getActionCommand() = "
+ group.getSelection().getActionCommand());
for (var b : buttons) b.setActionCommand(b.getText());
System.out.println("after setActionCommand on each button = "
+ group.getSelection().getActionCommand());
group.clearSelection();
System.out.println("after clearSelection: " + group.getSelection());
}
static String selectedNames(List<JRadioButton> buttons) {
return buttons.stream().filter(AbstractButton::isSelected).map(AbstractButton::getText).toList().toString();
}
static void borders() {
System.out.println();
System.out.println("== Borders: the space each one takes (insets) ==");
var c = new JPanel();
Border[] borders = {
BorderFactory.createEmptyBorder(5, 10, 5, 10),
BorderFactory.createLineBorder(Color.GRAY, 3),
new LineBorder(Color.GRAY, 1, true),
BorderFactory.createEtchedBorder(),
BorderFactory.createLoweredBevelBorder(),
new SoftBevelBorder(BevelBorder.RAISED),
BorderFactory.createMatteBorder(1, 4, 1, 0, Color.BLUE),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.GRAY, 2),
BorderFactory.createEmptyBorder(6, 6, 6, 6)),
};
for (Border b : borders) {
Insets i = b.getBorderInsets(c);
System.out.printf(" %-18s top %2d left %2d bottom %2d right %2d%n",
b.getClass().getSimpleName(), i.top, i.left, i.bottom, i.right);
}
TitledBorder titled = BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Size");
c.setBorder(titled);
System.out.println(" panel border: " + c.getBorder().getClass().getSimpleName()
+ " \"" + titled.getTitle() + "\", justification LEADING: "
+ (titled.getTitleJustification() == TitledBorder.LEADING));
}
static void comboBoxes() {
System.out.println();
System.out.println("== JComboBox<String> ==");
var faces = new JComboBox<String>();
List<String> events = new ArrayList<>();
faces.addActionListener(_ -> events.add("action: " + faces.getSelectedItem()));
faces.addItem("Serif"); // first item is selected automatically
faces.addItem("SansSerif");
faces.addItem("Dialog");
faces.insertItemAt("Monospaced", 0);
System.out.println("items: " + items(faces) + ", selected " + faces.getSelectedItem()
+ " at index " + faces.getSelectedIndex());
faces.setSelectedIndex(2);
String face = faces.getItemAt(faces.getSelectedIndex()); // typed, no cast
System.out.println("selected with type String: " + face);
faces.removeItem("Monospaced");
System.out.println("after removeItem: " + items(faces) + ", selection " + faces.getSelectedItem());
events.forEach(e -> System.out.println(" " + e));
faces.setEditable(true);
faces.setSelectedItem("Fantasy"); // as if typed into the editor
System.out.println("editable, typed \"Fantasy\": selected item " + faces.getSelectedItem()
+ ", index " + faces.getSelectedIndex() + ", list unchanged " + items(faces));
var model = new DefaultComboBoxModel<Integer>();
List<Integer> sizes = new ArrayList<>();
for (int s = 8; s <= 72; s += 2) sizes.add(s);
model.addAll(sizes);
model.setSelectedItem(12);
var sizeBox = new JComboBox<>(model);
System.out.println("model with " + sizeBox.getItemCount() + " sizes, selected "
+ sizeBox.getItemAt(sizeBox.getSelectedIndex()));
record Unit(String symbol, double factor) {
@Override public String toString() { return symbol; } // what the combo box displays
}
var units = new JComboBox<>(new Unit[] {new Unit("mm", 1), new Unit("cm", 10), new Unit("in", 25.4)});
units.setSelectedIndex(2);
Unit u = units.getItemAt(units.getSelectedIndex());
System.out.println("object items shown via toString: " + u + ", factor " + u.factor());
}
static List<String> items(JComboBox<String> box) {
List<String> list = new ArrayList<>();
for (int i = 0; i < box.getItemCount(); i++) list.add(box.getItemAt(i));
return list;
}
static void sliders() {
System.out.println();
System.out.println("== JSlider ==");
var plain = new JSlider();
System.out.println("default: min " + plain.getMinimum() + ", max " + plain.getMaximum()
+ ", value " + plain.getValue() + ", horizontal "
+ (plain.getOrientation() == SwingConstants.HORIZONTAL));
var slider = new JSlider(0, 100, 50);
List<String> changes = new ArrayList<>();
slider.addChangeListener(e -> {
var s = (JSlider) e.getSource();
changes.add(s.getValue() + (s.getValueIsAdjusting() ? " (dragging)" : ""));
});
slider.setValueIsAdjusting(true); // what the UI does during a drag
slider.setValue(57);
slider.setValue(61);
slider.setValueIsAdjusting(false);
slider.setValue(150); // clamped to the maximum
slider.setValue(150); // no change, no event
System.out.println("change events: " + changes);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
List<Integer> keys = new ArrayList<>();
var it = slider.getLabelTable().keys();
while (it.hasMoreElements()) keys.add((Integer) it.nextElement());
Collections.sort(keys);
System.out.println("generated label positions: " + keys);
var labels = new java.util.Hashtable<Integer, JComponent>();
String[] letters = {"A", "B", "C", "D", "E", "F"};
for (int i = 0; i < letters.length; i++) labels.put(i * 20, new JLabel(letters[i]));
slider.setLabelTable(labels);
System.out.println("custom label at 40: " + ((JLabel) slider.getLabelTable().get(40)).getText());
var shared = new DefaultBoundedRangeModel(30, 0, 0, 100);
var a = new JSlider(shared);
var b = new JProgressBar(shared);
a.setValue(75);
System.out.println("slider and progress bar share a model: progress = "
+ b.getValue() + " (" + Math.round(b.getPercentComplete() * 100) + "%)");
}
static void spinnersAndLists() {
System.out.println();
System.out.println("== JSpinner and JList ==");
var spinner = new JSpinner(new SpinnerNumberModel(5, 0, 10, 5));
spinner.setValue(10);
System.out.println("number spinner at " + spinner.getValue() + ", next "
+ spinner.getNextValue() + ", previous " + spinner.getPreviousValue());
var days = new JSpinner(new SpinnerListModel(List.of("Mon", "Tue", "Wed")));
days.setValue(days.getNextValue());
System.out.println("list spinner moved to " + days.getValue());
var list = new JList<>(new String[] {"red", "green", "blue", "cyan"});
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setSelectedIndices(new int[] {0, 2, 3});
System.out.println("list selection: " + list.getSelectedValuesList()
+ ", visible rows " + list.getVisibleRowCount());
}
}
== Check boxes: one listener reads both states ==
start: bold=true, italic=false
style -> BOLD+ITALIC
style -> ITALIC
style -> PLAIN
setSelected(true) fires no action event:
style still PLAIN, but bold is now true
== Radio buttons in a ButtonGroup ==
item event on Large: SELECTED
size = 18, selected: [Large]
item event on Large: DESELECTED
size = 8, selected: [Small]
group.getSelection().getActionCommand() = null
after setActionCommand on each button = Small
after clearSelection: null
== Borders: the space each one takes (insets) ==
EmptyBorder top 5 left 10 bottom 5 right 10
LineBorder top 3 left 3 bottom 3 right 3
LineBorder top 1 left 1 bottom 1 right 1
EtchedBorder top 2 left 2 bottom 2 right 2
BevelBorder top 2 left 2 bottom 2 right 2
SoftBevelBorder top 3 left 3 bottom 3 right 3
MatteBorder top 1 left 4 bottom 1 right 0
CompoundBorder top 8 left 8 bottom 8 right 8
panel border: TitledBorder "Size", justification LEADING: true
== JComboBox<String> ==
items: [Monospaced, Serif, SansSerif, Dialog], selected Serif at index 1
selected with type String: SansSerif
after removeItem: [Serif, SansSerif, Dialog], selection SansSerif
action: Serif
action: SansSerif
editable, typed "Fantasy": selected item Fantasy, index -1, list unchanged [Serif, SansSerif, Dialog]
model with 33 sizes, selected 12
object items shown via toString: in, factor 25.4
== JSlider ==
default: min 0, max 100, value 50, horizontal true
change events: [50 (dragging), 57 (dragging), 61 (dragging), 61, 100]
generated label positions: [0, 20, 40, 60, 80, 100]
custom label at 40: C
slider and progress bar share a model: progress = 75 (75%)
== JSpinner and JList ==
number spinner at 10, next null, previous 5
list spinner moved to Tue
list selection: [red, blue, cyan], visible rows 8
Points to notice:
- The shared check box listener recomputed the style from both boxes after each click.
setSelected(true)changed the state without notifying it. - Selecting Small produced a
DESELECTEDitem event on Large. The group's selection model had anullaction command until the commands were set explicitly. - The two action events for the combo box came from adding the first item (Serif) and from
setSelectedIndex(2). Removing an unselected item fired nothing. - The slider reported the initial 50 when adjusting started, each dragged value marked "(dragging)", then the final value, and finally 100 for the clamped 150. Repeating
setValue(150)produced no event.
Common questions
How do I find which radio button is selected?
Set an action command on each button and read group.getSelection().getActionCommand(), or keep the buttons in a map from button to value and find the selected one. getSelection() returns a ButtonModel, not the button.
How do I clear all radio buttons in a group?
group.clearSelection() (Java 6). Calling setSelected(false) on the selected button doesn't work, because a group always keeps one selected once a selection was made.
How do I populate a combo box with objects but show a nice label?
Give the objects a toString() that returns the label (records work well), or install a ListCellRenderer that formats them. Read the choice with getItemAt(getSelectedIndex()) to keep the type.
Why does my combo box listener fire while I'm filling the box?
Adding the first item selects it and fires an action event. Fill a DefaultComboBoxModel first and then set it on the box, or add the listener after filling.
Slider or spinner? A slider for approximate values where position matters (volume, zoom, opacity); a spinner for exact numbers or dates, especially when the range is large. Many applications pair a slider with a spinner or text field that share the value.
API reference
| Class / method | Purpose |
|---|---|
JCheckBox(label), JCheckBox(label, selected), isSelected, setSelected | Check box. |
AbstractButton.addActionListener, addItemListener, doClick, setActionCommand | Button events and simulation. |
JRadioButton(label, selected), ButtonGroup.add, getSelection, clearSelection | Radio buttons and groups. |
BorderFactory.createEmptyBorder/LineBorder/EtchedBorder/LoweredBevelBorder/RaisedBevelBorder/MatteBorder/TitledBorder/CompoundBorder | Borders. |
createRaisedSoftBevelBorder(), createLoweredSoftBevelBorder(), createLineBorder(color, thickness, rounded), createDashedBorder(...), createStrokeBorder(...), Border.getBorderInsets, JComponent.setBorder | More borders (factory methods since Java 7). |
JComboBox<E>, addItem, insertItemAt, removeItem, removeItemAt, removeAllItems, getItemAt, getSelectedIndex, getSelectedItem, setEditable, setModel | Combo box. |
DefaultComboBoxModel.addElement, addAll, setSelectedItem | Combo box model. |
JSlider(min, max, value), getValue, setValue, getValueIsAdjusting, addChangeListener | Slider. |
JSlider.setMajorTickSpacing, setMinorTickSpacing, setPaintTicks, setPaintLabels, setLabelTable, setSnapToTicks, setPaintTrack, setInverted | Slider decorations. |
JSpinner(model), SpinnerNumberModel, SpinnerListModel, SpinnerDateModel | Spinners. |
JList<E>, setSelectionMode, getSelectedValuesList, setVisibleRowCount, addListSelectionListener | Lists. |
Summary
- Check boxes are independent yes/no choices; give related boxes a shared listener that reads all of them. Action events report user clicks; item events report every state change.
- Radio buttons in a
ButtonGroupallow exactly one selection. The group is not a component; add the buttons to a panel too. To find the selection through the group, set action commands. - Borders from
BorderFactorygroup and pad components; titled and empty borders are the most useful. A border's insets reduce the space for the content. JComboBox<E>offers one of many items, optionally editable. UsegetItemAt(getSelectedIndex())for a typed result, and aDefaultComboBoxModelfor many items.JSliderpicks a value in a range; ticks and labels needsetPaintTicksandsetPaintLabels. WatchgetValueIsAdjustingfor expensive reactions.JSpinnerandJListcomplete the set.
Practice Questions
1. A program sets checkbox.setSelected(true) when loading saved settings, but the label's font does not change. The font is updated in an action listener. Why, and what are two fixes?
setSelected changes the model state and fires item events, but not action events; action events represent user actions such as clicks. Either call the update method explicitly after loading the settings, or listen for item events (addItemListener), which fire on every state change, including programmatic ones.
2. Five radio buttons are in a ButtonGroup but not added to any panel. What does the user see?
Nothing. A ButtonGroup is not a component; it only coordinates the selection state of its buttons. The buttons must also be added to a container (such as a JPanel) to be laid out and displayed.
3. Why does group.getSelection().getActionCommand() often return null, and how do you fix it?
getSelection returns the ButtonModel of the selected button, and a model's action command is null by default (the button falls back to its label text, but the model does not). Calling setActionCommand on each radio button sets the command on its model, after which the expression returns the command of the selected button.
4. For an editable JComboBox<String>, the user types "Fantasy", which is not in the list. What do getSelectedIndex() and getSelectedItem() return? Is "Fantasy" added to the list?
getSelectedIndex() returns -1, because the value is not one of the items, and getSelectedItem() returns the edited value, "Fantasy". The list of choices is not changed; to remember typed values, add them yourself with addItem.
5. A slider controls the zoom of a large image, and dragging it feels sluggish. What can you do in the change listener?
While the user drags, the slider fires a change event for every intermediate value. Check slider.getValueIsAdjusting() and skip the expensive work (or do only a cheap preview) while it returns true; perform the full update when the final event arrives with getValueIsAdjusting() returning false.
Previous: Swing Text Components: Text Fields, Labels, Password Fields and Text Areas
Next: Swing Menus, Toolbars and Tooltips: Mnemonics, Accelerators and Popup Menus
Related reading
- Invoking the Java Compiler from Code: JavaCompiler, Tasks and Diagnostics
- Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
- Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
- Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations

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.