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 JFrame 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 JFrame, 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 JFrame 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 JFrame containing two JPanels and a JButton. The first JPanel will hold a JLabel and JComboBox. The second JPanel will hold a JLabel and a JList. Only one JPanel (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 JPanels

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 GuiApp1.

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 Set as Main Project). Beneath the GuiApp1 folder should be a Source Packages folder with a packages folder called GuiApp1. This folder contains the main class called GuiApp1.java. 

Before we add any Java code, add the following imports to the top of the GuiApp1 class, between the package GuiApp1 line and the public class GuiApp1:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

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:

public static void main(String[] args) { // existing main method

new GuiApp1(); // add this line

This means that the first thing to do is to create a new GuiApp1 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 GuiApp1 class, so add a new method:

public GuiApp1
{

}

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 GuiApp1() method.

Building the Application Window Using a JFrame

Design Note: You might have seen Java code published that shows the class (i.e., GuiApp1) extended from a JFrame. 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 JFrame class is if you need to make a more specific type of JFrame (take a look at What is Inheritance? for more information on making a subclass).

As mentioned earlier, the first layer of the GUI is an application window made from a JFrame. To create a JFrame object, call the JFrame constructor:

JFrame guiFrame = new JFrame();

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:

guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

guiFrame.setTitle("Example GUI");

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

guiFrame.setSize(300,250);

Design Note: An alternative option for setting the size of the window is to call the pack() method of the JFrame 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 setSize() 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:

guiFrame.setLocationRelativeTo(null);

Adding the Two JPanels

The two lines here create values for the JComboBox and JList objects we'll be creating shortly, using two String arrays. This makes it easier to populate some example entries for those components:

String[] fruitOptions = {"Apple", "Apricot", "Banana"
 ,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
 
String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
 , "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
 , "Pepper", "Radish", "Shallot", "Spinach", "Swede"
 , "Turnip"};

Create the first JPanel Object

Now, let's create the first JPanel object. It will contain a JLabel and a JComboBox. All three are created via their constructor methods:

final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Fruits:");
JComboBox fruits = new JComboBox(fruitOptions);

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:
comboPanel.add(comboLbl);
comboPanel.add(fruits);

Create the Second JPanel Object

The second JPanel follows the same pattern. We'll add a JLabel and a JList and set the values of those components to be "Vegetables:" and the second String array vegOptions. The only other difference is the use of the setVisible() method to hide the JPanel. Don't forget there will be a JButton controlling the visibility of the two JPanels. For this to work, one needs to be invisible at the start. Add these lines to set up the second JPanel

final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
JList vegs = new JList(vegOptions);
vegs.setLayoutOrientation(JList.HORIZONTAL_WRAP);
 
listPanel.add(listLbl);
listPanel.add(vegs);

One line worth noting in the above code is the use of the setLayoutOrientation() method of the JList. The HORIZONTAL_WRAP value makes the list display the items it contains in a 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 JButton to control the visibility of the JPanels. The value passed in the JButton constructor sets the label of the button:

JButton vegFruitBut = new JButton( "Fruit or Veg");

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. JButton 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:

vegFruitBut.addActionListener(new ActionListener()
{
 @Override
 public void actionPerformed(ActionEvent event)
 {
 //When the fruit of veg button is pressed
 //the setVisible value of the listPanel and
 //comboPanel is switched from true to 
 //value or vice versa.
 listPanel.setVisible(!listPanel.isVisible());
 comboPanel.setVisible(!comboPanel.isVisible());

 }
});

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 JPanels.

Add the JPanels to the JFrame

Finally, we need to add the two JPanels  and JButton to the JFrame. By default, a  JFrame uses the BorderLayout layout manager. This means there are five areas (across three rows) of the JFram that can contain a graphical component (NORTH, {WEST, CENTER, EAST}, SOUTH). Specify this area using the add() method:

guiFrame.add(comboPanel, BorderLayout.NORTH);
guiFrame.add(listPanel, BorderLayout.CENTER);
guiFrame.add(vegFruitBut,BorderLayout.SOUTH);

Set the JFrame to Be Visible

Finally all of the above code will have been for nothing if we don't set the  JFrame to be visible:

guiFrame.setVisible(true);

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.