IntelliJ IDEA
 
Get IntelliJ IDEA

Tutorial: Build UI using Swing

Last modified: 15 October 2024

The UI Designer plugin in IntelliJ IDEA enables you to create graphical user interfaces (GUI) for your applications using the Swing library components. Using UI Designer, you can quickly create dialogs and groups of controls to be used in top-level containers, such as JFrame. These elements can coexist with the components that you define directly in your Java code.

In this tutorial, you will learn the basics of working with UI Designer and try creating your own GUI form for a sample application. As an exercise, we will build a GUI form for editing the information about a book, such as its title, author, genre, and availability status.

At the end of the tutorial, your form will look similar to the following example:

Example GUI form

IntelliJ IDEA stores the information about GUI forms that you create in .form files. A form can be associated with a Java source file and put under version control.

As a first step, we will create a new GUI form and an associated Java class for it.

Our project now has a BookEditor.form file and BookEditor.java file. The BookEditor.form file is where we will arrange the GUI components and set their properties. The BookEditor.java file will contain the code that will make our form functional.

Next, let us continue by building out our form and incorporating the required fields, checkboxes, and controls into our Book editor.

First, we can work on the JPanel component which acts as a container to store the GUI you want to build.

Our field names currently do not have any labels and are unrecognizable to end users. The Swing library provides a specific component, JLabel, that you can use to add any text labels to your GUI form.

For the checkbox, adding a label is not required, since you can configure the text directly in the JCheckBox component properties.

We want our Book editor to have the ability to save and discard the changes made by the end user. For this purpose, let us add the Save and Cancel buttons.

Now that we have all the necessary Swing components placed to the GUI form, let us check the intermediate results and learn how the form will look at runtime.

At this stage, our GUI form is a little raw. Let us improve the look and feel of it by adjusting the margins and setting up the preferred window size.

Now that the GUI form is ready, you can make it functional by editing the content in BookEditor.java. Functionality for the form in this tutorial has been prepared and is available in BookEditorExample.java which can be found under src/com/example/library/forms/BookEditorExample.