Please enable JavaScript to use CodeHS

Java Swing Buttons - Layout

In this tutorial, students will leave about different button components such as buttons, radio buttons, and checkboxes. Students will be adding these into a basic layout in Java Swing.

By David Burnham

Once you get the basic idea of Java Swing layouts (see this tutorial for more info), you are ready to start adding different components. In this tutorial, you are going to look at three common components: a basic button; checkboxes; and radio buttons. While the purpose of these components is to convey an action, this tutorial is just going to look at adding them into a layout. Other tutorials will look at how to add actions to components.


Buttons

A common button is relatively straightforward to add and can be as simple as creating the button and adding it to the pane:


JButton button1 = new JButton(buttonText);
pane.add(button1);


Beyond the basics, you have options to style the button, including setting a background color and preferred size.


In the example below, you will see how a title bar is created and styled, then two buttons are added to a Flow Pane. Take time to see how these buttons are styled and play around to add your own styling to the buttons.

Checkboxes

Checkboxes are also a common tool on a GUI app. A checkbox is a box that can be either checked or unchecked independent of any other checkboxes on the page.


Like buttons, checkboxes can be relatively easy to add.


JCheckBox cb1 = new JCheckBox("Option 1");
pane.add(cb1);


Just like buttons, checkboxes have a default background that is visible, but they do not have a natural border around them like a button. As a result, you would typically and to set the box to opaque.


Notice in the example below how the checkboxes are added to a panel and the panel is added into the flow pane to help maintain the layout.

Radio Buttons

Radio buttons are similar to checkboxes, however, only one option can be checked at a time.


The basic layout for a radio button is the same as checkboxes. You will create them, set them to opaque, and add them to an individual panel.


Radio buttons do require one more step though. As mentioned above, only one option can be selected at any one point in time, but what happens if you want to have two different sets of radio buttons? To tell Java which buttons belong together, you need to create a `ButtonGroup` object and add the buttons to that button group. Once added to a `ButtonGroup`, Java will only allow one button to be selected from that group.


In the example below, notice how two different button groups are used, one for options A, B, and C and one for options X, Y, and Z. The user can select one option for each group. Try moving some of the radio buttons from group 1 to group 2 and see the results.