Java Programming Examples: Creating a GUI with Swing

programmingWhen you are learning how to program in Java, one of the best ways to see proper code in action is to follow along with examples. These examples can be plugged into your own text editor or Java IDE and you can experiment with them as you learn about various Java components.  If you are brand new to Java programming, make sure you check out Java Fundamentals before attempting the examples in this tutorial.

Your very first program was probably a console-based application. In other words, you used the Windows Commands Prompt to execute your program in text format. These simple applications have no Graphical User Interface (GUI) and although you can do some cool things in the console, it won’t be long before you want to start creating graphical applications like the professionals.

Fortunately, Java offers the Swing API. This class library allows you to create powerful GUI components very easily and does not require the use of a separate IDE (although it does make it much easier). In this tutorial, you will learn how to make the famous “Hello World” program using a GUI instead of the boring console view.

What is Swing?

Swing is part of the Java Foundation Classes (JFC for short). This is a group of features specifically designed for building GUIs and adding rich graphic functionality and interactivity to your Java applications. The main components of the JFC include:

Swing GUI Components – This includes everything from buttons to split panes to tables. Many of these components are capable of sorting, printing, and drag-and-drop functionality as well as a few other supported features.

Pluggable Look and Feel Support – Swing applications can easily take on the appearance of other popular programs. For instance, by default you can set your swing applications to have the look and feel of Java or Windows. The Java platform also supports GTK+ look and feel; making hundreds of other “look and feels” available to your Swing-based programs.

Accessibility API – These components enable assistive technologies such as screen readers and braille displays.

Java 2-D API – This class library enables you to incorporate high-quality 2-D graphics, text, and images into your applications and applets. Many popular Java games are written using the Java 2-D API exclusively.  You can learn more about creating simple Java games in Learn Java from Scratch.

There are a few other components of JFC as well, but the Swing GUI Components are what you need to know about for this tutorial.

In total, the Swing API has 18 public packages. For most applications, however, you only need to import javax.swing.*.

You can learn more about the available Swing packages in the Java Swing Programming course.

Creating the Hello World GUI

This tutorial assumes that you already have a functional version of the Java SDK on your computer. If you do not, you can learn more about setting up a Java environment on your PC in the Introduction to Java Training Course.

Below you will find the code to create your very own Hello World GUI based Java Swing application. Open up your favorite text editor and add this code exactly as you see it to create this program:

import javax.swing.JFrame;

import javax.swing.JLabel;

 

//import statements

public class HelloWorldFrame extends JFrame {

 

        public static void main(String args[]) {

                    new HelloWorldFrame();

        }

        HelloWorldFrame() {

                    JLabel jlbHelloWorld = new JLabel(“Hello World”);

                    add(jlbHelloWorld);

                    this.setSize(100, 100);

                    // pack();

                    setVisible(true);

        }

}

Make sure to save the program in the text editor as HelloWorldFrame.java. Now that you have created the program in a text editor, you have to compile and run the program using the command prompt as follows:

javac HelloWorldFrame.java

and then to run it…

java HelloWorldFrame.java

A small window should now pop up displaying “Hello World.” Congratulations! You have just successfully completed your first Java application using a GUI.

As you can see, the JFrame is the key component used in this example. The JFrame is responsible for creating the small application window that appears on your screen. A JFrame is a window with a title, border, and an optional menu bar as well as user-specified components within the JFrame. It can be moved and resized by the user or you can set default sizes within the application.

For instance, by default a JFrame is displayed in the upper left corner of the screen. You can adjust where the JFrame loads by default by using the setLocation(x,y) method within the JFrame class. This method places the upper left corner of the JFrame at the location you specify.

The other important element in this example is the JLabel. JLabels are used in the Swing GUI when a user interface component that displays a message or an image is needed. Notice that you can also include an image within a JLabel; a feature you will rely on heavily as you become more acquainted with using Swing. If you want to add an image to this example, simply modify the JLabel and reference the image within the JLabel constructor like this:

import javax.swing.JFrame;

import javax.swing.JLabel;

 

//import statements

public class HelloWorldFrame extends JFrame {

 

        public static void main(String args[]) {

                    new HelloWorldFrame();

                    ImageIcon icon = createImageIcon (“images/example.jpg”);

        }

        HelloWorldFrame() {

                    JLabel jlbHelloWorld = new JLabel(“Hello World”, icon);

                    add(jlbHelloWorld);

                    this.setSize(100, 100);

                    // pack();

                    setVisible(true);

        }

}

As you can see, the bold areas in the example above are code that has been added to create the image in the JLabel. The createImageIcon method is where you put the source of your image and you simply need to refer to the image object (called “icon” in this example) to include the image in your application.

Obviously, this is only scratching the surface of the power of Swing. Many robust GUIs have been built using Swing alone and it provides many interesting features that can be appreciated by beginners and experienced programmers alike.

It’s always helpful to learn how to code Java before relying heavily on an IDE such as Eclipse.  That said, most Swing components are drag-and-drop capable in IDEs; saving you a lot of development time.  If you want to learn more about using Eclipse to create your programs, check out Java Programming Using Eclipse.

If you are ready to take your Java programming to the next level, Swing is the way to do it. Your applications will be much more fun and interesting when you are creating GUIs that you can actually interact with.