Choice Components Core Java

You now know how to collect text input from users, but there are many occasions for which you would rather give users a finite set of choices than have them enter the data in a text component. Using a set of buttons or a list of items tells your users what choices they have. (It also saves you the trouble of error checking.) In this section, you learn how to program checkboxes, radio buttons, lists of choices, and sliders.


If you want to collect just a “yes” or “no” input, use a check box component. Check boxes automatically come with labels that identify them. The user usually checks the box by clicking inside it and turns off the check mark by clicking inside the box again. To toggle the check mark, the user can also press the space bar when the focus is in the checkbox. a simple program with two checkboxes, one to turn on or off the italic attribute of a font, and the other for bold face. Note that the second check box has focus, as indicated by the rectangle around the label. Each time the user clicks one of the check boxes, the screen is refreshed, using the new font attributes.



Checkboxes need a label next to them to identify their purpose. You give the label text in the constructor.

You use the setSelected method to turn a checkbox on or off. For example:

The isSelected method then retrieves the current state of each checkbox. It is false if unchecked; true if checked.

When the user clicks on a checkbox, this triggers an action event. As always, you attach an action listener to the checkbox. In our program, the two checkboxes share the same action listener.

The action Performed method queries the state of the bold and italic check boxes and sets the font of the panel to plain, bold, italic, or both bold and italic.

javax.swing.JCheckBox 1.2

  • JCheckBox(String label)
  • JCheckBox(String label, Icon icon)
    constructs a checkbox that is initially unselected.
  • JCheckBox(String label, boolean state)
    constructs a checkbox with the given label and initial state.
  • boolean isSelected ()
  • void setSelected(boolean state)
    gets or sets the selection state of the checkbox.

Radio Buttons

In the previous example, the user could check either, both, or neither of the two checkboxes. In many cases, we want to require the user to check only one of several boxes. When another box is checked, the previous box is automatically unchecked. Such a group of boxes is often called a radio button group because the buttons work like the station selector buttons on a radio. When you push in one button, the previously depressed button pops out. a typical example. We allow the user to select a font size from among the choices —Small, Medium, Large, and Extra large—but, of course, we will allow the user to select only one size at a time.

A radio button group

A radio button group

Implementing radio button groups is easy in Swing. You construct one object of type Button Group for every group of buttons. Then, you add objects of type JRadio Button to the button group. The button group object is responsible for turning off the previously set button when a new button is clicked.

The second argument of the constructor is true for the button that should be checked initially and false for all others. Note that the button group controls only the behavior of the buttons; if you want to group the buttons for layout purposes, you also need to add them to a container such as a JPanel.

If you look again at Figures below, you will note that the appearance of the radio buttons is different from that of checkboxes. Check boxes are square and contain a check mark when selected. Radio buttons are round and contain a dot when selected. The event notification mechanism for radio buttons is the same as for any other buttons.

When the user checks a radio button, the radio button generates an action event. In our example program, we define an action listener that sets the font size to a particular value:

Compare this listener setup with that of the checkbox example. Each radio button gets a different listener object. Each listener object knows exactly what it needs to do—set the font size to a particular value. In the case of the checkboxes, we used a different approach. Both checkboxes have the same action listener. It called a method that looked at the current state of both checkboxes.

Could we follow the same approach here? We could have a single listener that computes the size as follows:

However, we prefer to use separate action listener objects because they tie the size values more closely to the buttons.

javax.swing.JRadiobutton 1.2

  • JRadioButton(String label, Icon icon)
  • constructs a radio button that is initially unselected.
  • JRadioButton(String label, boolean state)
    constructs a radio button with the given label and initial state.
  • void add(AbstractButton b)
  • adds the button to the group.
  • ButtonModel getSelection()
    returns the button model of the selected button
  • String getActionCommand()
    returns the action command for this button model.
  • void setActionCommand(String s)
    sets the action command for this button and its model.


If you have multiple groups of radio buttons in a window, you will want to visually indicate which buttons are grouped. Swing provides a set of useful borders for this purpose. You can apply a border to any component that extends JComponent. The most common usage is to place a border around a panel and fill that panel with other user interface elements such as radio buttons.

You can choose from quite a few borders, but you follow the same steps for all of them.

  1. Call a static method of the BorderFactory to create a border. You can choose among the following styles:
    • Lowered bevel
    • Raised bevel
    • Etched
    • Line
    • Matte
    • Empty (just to create some blank space around the component)
  2. If you like, add a title to your border by passing your border to BorderFactory.createTitledBorder.
  3. If you really want to go all out, combine several borders with a call to Border Factory .create Compound Border.
  4. Add the resulting border to your component by calling the setBorder method of the JComponent class.

For example, here is how you add an etched border with a title to a panel:

Run the program in Listing below to get an idea what the various borders look like. The various borders have different options for setting border widths and colors. See the API notes for details. True border enthusiasts will appreciate that there is also a SoftBevelBorder class for beveled borders with softened corners and that a LineBorder can have rounded corners as well. You can construct these borders only by using one of the class constructors—there is no BorderFactory method for them.

Testing border types

Testing border types

javax.swing.BorderFactory 1.2

  • static Border createLineBorder(Color color)
  • static Border createLineBorder(Color color, int thickness)
    creates a simple line border.
  • static MatteBorder createMatteBorder(int top, int left, int bottom, int right, Color color)
  • static MatteBorder createMatteBorder(int top, int left, int bottom, int right, Icon tileIcon)
    creates a thick border that is filled with a color or a repeating icon.
  • static Border createEmptyBorder()
  • static Border createEmptyBorder(int top, int left, int bottom, int right)
    creates an empty border.
  • static Border createEtchedBorder()
  • static Border createEtchedBorder(Color highlight, Color shadow)
  • static Border createEtchedBorder(int type)
  • static Border createEtchedBorder(int type, Color highlight, Color shadow)
    creates a line border with a 3D effect.
  • static Border createBevelBorder(int type)
  • static Border createBevelBorder(int type, Color highlight, Color shadow)
  • static Border createLoweredBevelBorder()
  • static Border createRaisedBevelBorder()
    creates a border that gives the effect of a lowered or raised surface.
  • static TitledBorder createTitledBorder(String title)
  • static TitledBorder createTitledBorder(Border border)
  • static TitledBorder createTitledBorder(Border border, String title)
  • static TitledBorder createTitledBorder(Border border, String title, int justification,
    int position)
  • static TitledBorder createTitledBorder(Border border, String title, int justification,
    int position, Font font)
  • static TitledBorder createTitledBorder(Border border, String title, int justification,
    int position, Font font, Color color) creates a titled border with the specified properties.
  • static CompoundBorder createCompoundBorder(Border outsideBorder, Border insideBorder)
    combines two borders to a new border.
  • SoftBevelBorder(int type, Color highlight, Color shadow)
    creates a bevel border with softened corners.
  • public LineBorder(Color color, int thickness, boolean roundedCorners)
    creates a line border with the given color and thickness. If roundedCorners is true, the border has rounded corners.
  • void setBorder(Border border)
    sets the border of this component.

Combo Boxes

If you have more than a handful of alternatives, radio buttons are not a good choice because they take up too much screen space. Instead, you can use a combo box. When the user clicks on the component, a list of choices drops down, and the user can then select one of them.

A combo box

A combo box

If the drop-down list box is set to be editable, then you can edit the current selection as if it were a text field. For that reason, this component is called a combo box—it combines the flexibility of a text field with a set of predefined choices. The JComboBox class provides a combo box component.

You call the setEditable method to make the combo box editable. Note that editing affects only the current item. It does not change the content of the list.

You can obtain the current selection or edited text by calling the getSelectedItem method.
In the example program, the user can choose a font style from a list of styles (Serif, Sans- Serif, Monospaced, etc.). The user can also type in another font.

You add the choice items with the addItem method. In our program, addItem is called only in the constructor, but you can call it any time.

This method adds the string at the end of the list. You can add new items anywhere in the list with the insert ItemAt method:

You can add items of any type—the combo box invokes each item’s toString method to display it. If you need to remove items at runtime, you use the removeItem or remove ItemAt method, depending on whether you supply the item to be removed or its position.

The removeAllItems method removes all items at once.

When the user selects an item from a combo box, the combo box generates an actionevent. To find out which item was selected, call getSource on the event parameter to get areference to the combo box that sent the event. Then call the getSelectedItem method toretrieve the currently selected item. You need to cast the returned value to the appropriatetype, usually String.

javax.swing.JComboBox 1.2

  • boolean isEditable()
  • void setEditable(boolean b)
    gets or sets the editable property of this combo box.
  • void addItem(Object item)
    adds an item to the item list.
  • void insertItemAt(Object item, int index)
    inserts an item into the item list at a given index.
  • void removeItem(Object item)
    removes an item from the item list.
  • void removeItemAt(int index)
    removes the item at an index.
  • void removeAllItems()
    removes all items from the item list.
  • Object getSelectedItem()
    returns the currently selected item.


Combo boxes let users choose from a discrete set of values. Sliders offer a choice from a continuum of values, for example, any number between 1 and 100.

The most common way of constructing a slider is as follows:

If you omit the minimum, maximum, and initial values, they are initialized with 0, 100, and 50, respectively.

Or if you want the slider to be vertical, then use the following constructor call:

These constructors create a plain slider, such as the top slider. You will see presently how to add decorations to a slider.



As the user slides the slider bar, the value of the slider moves between the minimum and the maximum values. When the value changes, a ChangeEvent is sent to all change listeners.

To be notified of the change, you call the addChangeListener method and install an object that implements the ChangeListener interface. That interface has a single method, stateChanged. In that method, you should retrieve the slider value:

You can embellish the slider by showing ticks. For example, in the sample program, the second slider uses the following settings:

The slider is decorated with large tick marks every 20 units and small tick marks every 5 units. The units refer to slider values, not pixels. These instructions only set the units for the tick marks. To actually have the tick marks appear, you also call

The major and minor tick marks are independent. For example, you can set major tick marks every 20 units and minor tick marks every 7 units, but you’ll get a very messy scale.
You can force the slider to snap to ticks. Whenever the user has finished dragging a slider in snap mode, it is immediately moved to the closest tick. You activate this mode with the call

You can ask for tick mark labels for the major tick marks by calling

For example, with a slider ranging from 0 to 100 and major tick spacing of 20, the ticks are labeled 0, 20, 40, 60, 80, and 100.

You can also supply other tick marks, such as strings or icons. The process is a bit convoluted. You need to fill a hash table with keys of type Integer and values of type Component. (Auto boxing makes this simple in Java SE 5.0 and beyond.) You then call the set Label Table method. The components are placed under the tick marks.

Usually, you use JLabel objects. Here is how you can label ticks as A, B, C, D, E, and F:
Hashtable<Integer, Component> labelTable = new Hashtable<Integer, Component>();

Listing below also shows a slider with icons as tick labels. The fourth slider in has no track. To suppress the “track” in which the slider moves, call

The fifth slider has its direction reversed by a call to

The example program shows all these visual effects with a collection of sliders. Each slider has a change event listener installed that places the current slider value into the text field at the bottom of the frame.

javax.swing.JSlider 1.2

  • JSlider()
  • JSlider(int direction)
  • JSlider(int min, int max)
  • JSlider(int min, int max, int initialValue)
  • JSlider(int direction, int min, int max, int initialValue) .constructs a horizontal slider with the given direction and minimum, maximum, and initial values.
  • void setPaintTicks(boolean b)
    displays ticks if b is true.
  • void setMajorTickSpacing(int units)
  • void setMinorTickSpacing(int units)
    sets major or minor ticks at multiples of the given slider units.
  • void setPaintLabels(boolean b)
    displays tick labels if b is true.
  • void setLabelTable(Dictionary table)
    sets the components to use for the tick labels. Each key/value pair in the table has the form new Integer(value)/component.
  • void setSnapToTicks(boolean b)
    if b is true, then the slider snaps to the closest tick after each adjustment.
  • void setPaintTrack(boolean b)
    if b is true, then a track is displayed in which the slider runs.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics