Java GUI Tutorial: Mastering the Basics

javaguitutorialLearning to program in Java can be both fun and exciting. It is one of the most popular programming languages that new programmers learn and it can be used in everything from standalone desktop applications to complex enterprise-level web applications.

When learning Java, your first programs are likely console programs. This means there is no Graphical User Interface (GUI) and all input and output is accomplished via the command line. Although you can do some pretty cool things in the console, it won’t be long before you want to create your own GUIs and begin interacting with your programs. In this tutorial, you will learn the basic concepts of creating your own GUI in Java. It is assumed you have a basic understanding of Java programming already. If you do not, please consider checking out Java Fundamentals I & II first.

In addition to this tutorial, you should refer to the Java API. This documentation explains every class library and how to incorporate them into your own programs. This is an excellent way to familiarize yourself with the thousands of classes available and can help make the examples used within this tutorial make sense if you are having difficulty understanding some of these concepts.

Terminology

To understand basic Java GUI concepts, you should understand a few terms and how they relate to your Java programs. These terms include:

Frame – The frame is the actual window where all of your program’s components are held. Text fields, radio buttons, labels,  and menus are all contained within the frame. Every Java application runs within a window and every window needs a frame where various components can “live.”

Content Pane – Sometimes also known simply as the pane, the content pane is where all of your programs components are placed. You can think of the content pane as a background and the various components of your program are painted onto this background.

Layout Manager – The layout manager aligns components within content pane into a specific style depending on what layout you choose. When you’re first starting out, layout managers can make component placement much easier, but they can also create additional complications not typically experienced when you set your layout manager to “null” and assign exact coordinates for every component.

Coordinates – Especially important when you are not using a layout manager, coordinates are used to specify where components are placed on the content pane. Coordinates are described just like x-y graphs from high school math class (X, Y). You can specify the exact position of components in your program by setting these coordinates. Please note that the coordinates refer to the components’ position relative to the top left of the pane.

These concepts are explained further in Java Swing Programming: From Beginner to Expert.

Creating a Basic GUI

This basic program computes the area of a rectangle using GUI components.

In order to create a GUI, the first step is to import the necessary class libraries. In this example, you need to import javax.swing.JFrame, java.awt.event, and java.awt.*.

Next, you need to create a frame. Your Java class needs to extend the JFrame class in order to create the frame like this:

public class RectangleAreaCalculator extends JFrame

In addition to creating a class that extends JFrame, you also need to define some frame attributes such as dimensions, title, and visibility. The finished code for the JFrame looks like this:

import javax.swing.JFrame;

import java.awt.*;

 

public class RectangleAreaCalculator extends JFrame

{

        private static final int HEIGHT = 400;

private static final int WIDTH = 700;

               

        public RectangleAreaCalculator()

        {

                    setTitle(“Rectangle Area Calculator”);

                    setSize(WIDTH, HEIGHT);

                    setVisible(true);

                    setDefaultCloseOperation(EXIT_ON_CLOSE);

        }

       

}

Note that the visibility of the frame must be set to “true” for the frame to be visible on the computer. As simple as this seems, many beginners forget to add this attribute and don’t understand why their program is not showing up on the computer screen.

Once the JFrame has been successfully created, the next step is to create a content pane. This is done using the Container object and this class only has two methods (add and setLayout). You will see how the add method works in the final code example. For now, focus on using setLayout to use a specific layout manager for your program. The code looks like this:

Container pane = getContentPane();

pane.setLayout(new GridLayout (4, 2));

Notice that the simple grid layout created with the above code calls for a layout with four rows and two columns. This layout manager automatically places your GUI component into a uniformly spaced grid layout.

The next step is to add components to your program. In this example, you will only be using three components known as JLabel, JTextField, and JButton. These should be declared and instantiated in the same manner as objects in console programs you may have previously written. Again, if you’re unfamiliar with these basic Java concepts, check out Java for Absolute Beginners.

Once the components have been declared and instantiated, the next step is to add them to the content pane using the pane.add() method.

Now that all the components have been added to the content pane, you need to tell the program how to respond when a user interacts with these components. This is accomplished using the abstract method actionPerformed (which requires a registered ActionListener).

Finally, a main method needs to be added for this program to run. Since just about every part of this program was created within the constructor, the main method only contains one line as you will see below.

Below you’ll find the completed code that builds upon the concepts discussed above. Take your time going through this code to understand how each component works and feel free to copy it into your favorite text editor and compile it as a Java program to see how this program actually functions.

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

 

 

public  class RectangleAreaCalculator extends JFrame

{

  

        private JLabel lengthLabel, widthLabel, areaLabel;

        private JTextField lengthText, widthText, areaText;

        private JButton calculateButton, exitButton;

 

private static final int HEIGHT = 400;

        private static final int WIDTH = 700;

       

           private CalculateButtonHandler calculateButtonHandler;

        private ExitButtonHandler exitButtonHandler;

       

        public RectangleAreaCalculator()

        {

                    lengthLabel = new JLabel(“Please enter the rectangle’s length: “);

                    widthLabel = new JLabel(“Please enter the rectangles’s width: “);

                    areaLabel = new JLabel(“The Area is: “, SwingConstants.RIGHT);

                   

                    lengthText = new JTextField(12);

                    widthText = new JTextField(12);

                    areaText = new JTextField(12);

                   

                    //This section specifies the handlers for the buttons and adds an ActionListener.

                    calculateButton = new JButton(“What’s the Area?”);

                    calculateButtonHandler = new CalculateButtonHandler();

                    calculateButton.addActionListener(calculateButtonHandler);

                    exitButton = new JButton(“Close”);

                    exitButtonHandler = new ExitButtonHandler();

                    exitButton.addActionListener(exitButtonHandler);

                   

                    setTitle(“Rectangle Area Calculator”);

                    Container pane = getContentPane();

                    pane.setLayout(new GridLayout(4, 2));

                   

                    //Grid layout requires that you add components to the content pane in the order they should appear

                    pane.add(lengthLabel);

                    pane.add(lengthText);

                    pane.add(widthLabel);

                    pane.add(widthText);

                    pane.add(areaLabel);

                    pane.add(areaText);

                    pane.add(calculateButton);

                    pane.add(exitButton);

                   

                    setSize(HEIGHT, WIDTH);

                    setVisible(true);

                    setDefaultCloseOperation(EXIT_ON_CLOSE);

        }

       

        private class CalculateButtonHandler implements ActionListener

        {

                    public void actionPerformed(ActionEvent e)

                    {

                                double width, length, area;

                               

                                length = Double.parseDouble(lengthText.getText());                                  width = Double.parseDouble(widthText.getText());

                                area = length * width;

                               

                                areaText.setText(“” + area);

                    }

        }

       

        public class ExitButtonHandler implements ActionListener

        {

                    public void actionPerformed(ActionEvent e)

                    {

                                System.exit(0);

                    }

        }

       

        public static void main(String[] args)

        {

                    RectangleAreaCalculator rectObj = new RectangleAreaCalculator();

        }

       

}

That’s it! You have successfully created your very first Java GUI program. Although this program is relatively simple, it does demonstrate most of the major GUI components you will be using as you begin to create more advanced programs with graphical interfaces.

If you aren’t doing so already, you can make GUI creation even easier using an IDE such as Eclipse.  The Introduction to Java Programming with Eclipse course helps you transition into the world of IDE Java development.

Feel free to play around with this code and make changes to see how they affect the program at runtime. Trial and error is the absolute best way to learn what works and what doesn’t when you start programming your very own GUIs in Java.