Coding a Simple Java User Interface Using NetBeans and Swing

Young businessman holding his head and pondering

Hinterhaus Productions/Getty Images

A graphical user interface (GUI) built using the Java NetBeans platform is made up of several layers of containers. The first layer is the window used to move the application around the screen of your computer. This is known as the top-level container, and its job is to give all other containers and graphical components a place to work in. Typically for a desktop application, this top-level container will be made using the 

class.

You can add any number of layers to your GUI design, depending on its complexity. You can place graphical components (e.g., text boxes, labels, buttons) directly into the 

, or you can group them in other containers.

The layers of the GUI are known as the containment hierarchy and can be thought of as a family tree. If the 

is the grandfather sitting at the top, then the next container can be thought of as the father and the components it holds as the children.

For this example, we'll build a GUI with a 

containing two

and a

. The first

will hold a

and

. The second

will hold a

and a

. Only one

(and hence the graphical components it contains) will be visible at a time. The button will be used to switch the visibility of the two

.

There are two ways to build this GUI using NetBeans. The first is to manually type in the Java code that represents the GUI, which is discussed in this article. The second is to use the NetBeans GUI Builder tool for building Swing GUIs.

For information on using JavaFX rather than Swing to create a GUI, see What is JavaFX?

Note: The complete code for this project is at Example Java Code for Building A Simple GUI Application.

Setting Up the NetBeans Project

Create a new Java Application project in NetBeans with a main class We'll call the project

Check Point: In the Projects window of NetBeans should be a top-level GuiApp1 folder (if the name is not in bold, right-click the folder and choose

). Beneath the

folder should be a Source Packages folder with

called GuiApp1. This folder contains the main class called

.java.

Before we add any Java code, add the following imports to the top of the

class, between the

line and the

:

These imports mean that all the classes we need to make this GUI application will be available for us to use.

Within the main method, add this line of code:

This means that the first thing to do is to create a new 

object. It's a nice short-cut for example programs, as we only need one class. For this to work, we need a constructor for the

class, so add a new method:

In this method, we'll put all the Java code needed to create the GUI, meaning that every line from now on will be inside the

method.

Building the Application Window Using a JFrame

Design Note: You might have seen Java code published that shows the class (i.e.,

) extended from a

. This class is then used as the main GUI window for an application. There really isn't any need to do this for a normal GUI application. The only time you would want to extend the

class is if you need to make a more specific type of

(take a look at

for more information on making a subclass).

As mentioned earlier, the first layer of the GUI is an application window made from a

. To create a

object, call the

constructor:

Next, we'll set the behavior of our GUI application window, using these four steps:

1. Ensure that the application closes when the user closes the window so that it does not continue to run unknown in the background:

2. Set a title for the window so the window doesn't have a blank title bar. Add this line:

3. Set the window size, so that the window is sized to accommodate the graphical components you place into it.

Design Note: An alternative option for setting the size of the window is to call the

method of the

class. This method calculates the size of the window based on the graphical components it contains. Because this sample application doesn't need to change its window size, we'll just use ​the

method.

4. Center the window to appear in the middle of the computer screen so that it does not appear in the top left-hand corner of the screen:

Adding the Two JPanels

The two lines here create values for the

and

objects we'll be creating shortly, using two

arrays. This makes it easier to populate some example entries for those components:

Create the first JPanel Object

Now, let's create the first

object. It will contain a

and a

. All three are created via their constructor methods:

Notes on the above three lines:

  • The
    JPanel
    variable is declared final. This means that the variable can only hold the
    JPanel
    that's created in this line. The result is that we can use the variable in an inner class. It will become apparent why we want to later on in the code.
  • The
    JLabel
    and
    JComboBox
    have values passed to them to set their graphical properties. The label will appear as "Fruits:" and the combobox will now have the values contained within the
    fruitOptions
    array declared earlier.
  • The
    add()
    method of the
    JPanel
    places graphical components into it. A
    JPanel
    uses the FlowLayout as its default layout manager. This is fine for this application as we want the label to sit next to the combobox. As long as we add the
    JLabel
    first, it will look fine:

Create the Second JPanel Object

The second

follows the same pattern. We'll add a

and a

and set the values of those components to be "Vegetables:" and the second

array

. The only other difference is the use of the

method to hide the

. Don't forget there will be a

controlling the visibility of the two

. For this to work, one needs to be invisible at the start. Add these lines to set up the second

:

One line worth noting in the above code is the use of the

method of the

. The

value makes the list display the items it contains in two columns. This is called a "newspaper style" and is a nice way to display a list of items rather than a more traditional vertical column.

Adding Finishing Touches

The last component needed is the

to control the visibility of the

s. The value passed in the

constructor sets the label of the button:

This is the only component that will have an event listener defined. An "event" occurs when a user interacts with a graphical component. For example, if a user clicks on a button or writes text into a textbox, then an event occurs.

An event listener tells the application what to do when the event happens. 

uses the ActionListener class to "listen" for a button click by the user.

Create the Event Listener

Because this application performs a simple task when the button is clicked, we can use an anonymous inner class to define the event listener:

This may look like scary code, but you just have to break it down to see what is happening:

  • First, we call the
    addActionListener
    method of the
    JButton
    . This method expects an instance of the
    ActionListener
    class, which is the class that listens for the event.
  • Next, we create the instance of the 
    ActionListener
    class by declaring a new object using
    new ActionListener()
    and then providing an anonymous inner class — which is all the code inside the curly brackets.
  • Inside the anonymous inner class, add a method called
    actionPerformed()
    . This is the method that is called when the button is clicked. All that's needed in this method is to use 
    setVisible()
     to change the visibility of the
    JPanel
    s.

Add the JPanels to the JFrame

Finally, we need to add the two

s and

to the

. By default, a

uses the BorderLayout layout manager. This means there are five areas (across three rows) of the

that can contain a graphical component (NORTH, {WEST, CENTER, EAST}, SOUTH). Specify this area using the

method:

Set the JFrame to Be Visible

Finally, all of the above code will have been for nothing if we don't set the 

to be visible:

Now we're ready to run the NetBeans project to display the application window. Clicking on the button will switch between showing the combobox or list.