The Java Tutorials' Weblog

pageicon Thursday Mar 01, 2007

Early Access Lesson: Learning Swing with the NetBeans IDE

This blog entry is our first "Early Access" document. It is a work in progress... one that is currently up for technical review by engineering. As part of our early access initiative, we are allowing you, the reader, to comment on the document as we are writing it. We are still evaluating whether or not this approach will actually provide us with useful feedback; if you are reading this and would like to see more lessons posted as "works in progress", then leave us a comment!

This new lesson is an introduction to Swing using the NetBeans IDE. Feel free to comment on what you like, or what you would change, or whether or not you think the information is useful. This early access program is a bit of an experiment for us, so go ahead and tell us what you think!

-- Scott Hommel


Learning Swing with the NetBeans IDE

Early Access Draft: 3/1/2007

Introduction
Setting up the CelsiusConverter Project
    Step 1: Create a New Project
    Step 2: Choose General -> Java Application
    Step 3: Set a Project Name
    Step 4: Add a JFrame Form
    Step 5: Name the GUI Class
NetBeans IDE Basics
    The Palette
    The Design Area
    The Property Editor
    The Inspector
Creating the CelsiusConverterGUI
    Step 1: Set the Title
    Step 2: Add a JTextField
    Step 3: Add a JLabel
    Step 4: Add a JButton
    Step 5: Add a Second JLabel
Adjusting the GUI Components
    Step 1: Set the Component Text
    Step 2: Set the Component Size
    Step 3: Remove Extra Space
Adding the Application Logic
    Step 1: Change the Default Variable Names
    Step 2: Register the Event Listeners
    Step 3: Add the Temperature Conversion Code
    Step 4: Run the CelsiusConverter Application

Introduction

This lesson provides an introduction to Graphical User Interface (GUI) programming with Swing and the NetBeans IDE. As you learned in the getting started lesson, the NetBeans IDE is a free, open-source, cross-platform integrated development environment with built-in support for the Java programming language. It offers many advantages over coding at the command line; we recommend its use whenever possible. If you have not yet read the getting started lesson, please take a moment to do so now. It provides valuable information about downloading and installing the JDK and NetBeans IDE.

The goal of this lesson is to introduce the Swing API by designing a simple application that converts temperature from Celsius to Fahrenheit. Its GUI will be basic, focusing on only a subset of the available Swing components. The NetBeans IDE contains a GUI builder that makes user interface creation a simple matter of drag and drop. Its automatic code generation feature simplifies the GUI development process, letting you focus on the application logic instead of the underlying infrastructure.

Because this lesson is a step-by-step checklist of the specific actions to take within the NetBeans IDE, we recommend that you run the IDE yourself and perform each step as you read along. This will be the quickest and easiest way to begin programming with Swing. If you are unable to do so, simply reading along should still be useful, since each step is clearly illustrated with screenshots.

If you prefer the traditional approach of programming each component by hand (without the assistance of an IDE), you can think of this lesson as an entry point to the lower-level discussions that are already provided elsewhere in the tutorial. Hyperlinks in each discussion will take you to related lessons, should you feel the need to learn such lower-level details.

The GUI for the completed application will look as follows:


Figure 1: The CelsiusConverter Application

From an end-user's perspective, its usage is quite simple: enter a temperature (in Celsius) into the text box, click the "Convert" button, and watch the converted temperature (in Fahrenheit) appear in the lower right-hand corner. The minimize, maximize, and close buttons will behave as expected; as a final touch, the application will also have a title that appears along the top of the window.

From a programmer's perspective, we will write the application in two main stages. First, we will populate the GUI with its components and arrange them as shown in Figure 1. Then, we will add in the application logic, so that the program actually performs a conversion when the user presses the "Convert" button.

Setting Up the CelsiusConverter Project

If you have worked with the NetBeans IDE in the past, much of this section will look familiar, since the initial steps are similar for most projects. Still, the following steps describe settings that are specific to this application, so take care to follow them closely.

Step 1: Create a New Project


Figure 2: File -> New Project (Click to Enlarge)

To create a new project, launch the NetBeans IDE and choose New Project from the File menu. Note that keyboard shortcuts for each command appear on the far right of each menu item. The look and feel of the NetBeans IDE may vary across platforms, but the functionality will remain the same.

Step 2: Choose General -> Java Application


Figure 3: General -> Java Application (Click to Enlarge)

Next, select General from the Categories column, and Java Application from the Projects column. You may notice mention of "J2SE" in the description pane; that is just the old name for what is now known as the "Java SE" platform. Press the button labeled "Next" to proceed.

Step 3: Set a Project Name


Figure 4: New Java Application Window (Click to Enlarge)

Now enter "CelsiusConverter" as the project name. You can leave the Project Location and Project Folder fields set to their default values, or click the Browse button to choose an alternate location on your system.

Also make sure to deselect the "Create Main Class" checkbox. Leaving this option selected generates a new class as the main entry point for the application, but our main GUI window (created in the next step) will serve that purpose, so checking this box is not necessary.

Click the "Finish" button.


Figure 5: The Resulting Main Window (Click to Enlarge)

When the IDE finishes loading, you will see a screen similar to the above. All panes will be empty except for the Projects pane in the upper left hand corner, which shows the newly created CelsiusConverter project.

Step 4: Add a JFrame Form


Figure 6: New JFrame Form (Click to Enlarge)

Right-click the CelsiusConverter project name and choose New -> JFrame Form (JFrame is the Swing class responsible for the main frame for your application.) You will learn how to designate this class as the application's entry point later in this tutorial, after the application is complete.

Step 5: Name the GUI Class


Figure 7: New JFrame Form (Click to Enlarge)

Next, type CelsiusConverterGUI as the class name, and celsiusconverter as the package name. The remainder of the fields should automatically fill themselves in, as shown above in Figure 7. Click the Finish button when you are done.


Figure 8: The Design View (Click to Enlarge)

When the IDE finishes loading, the right pane will display a design-time, graphical view of the CelsiusConverterGUI. It is on this screen that you will visually drag, drop, and manipulate the various Swing components to construct the application's GUI.

NetBeans IDE Basics

You do not need to learn every feature of the NetBeans IDE before exploring its GUI creation capabilities. In fact, the only features that you really need to understand are the Palette, the Design Area, the Property Editor, and the Inspector.

The Palette

The Palette contains all of the components offered by Swing. You can probably already deduce what many of these components do, even if this is your first exposure to them (JLabel is a text label, JList is a drop-down list, etc.)


Figure 9: The Palette (Click to Enlarge)

From this list, the CelsiusConverterGUI will use only JLabel (a basic text label), JTextField (for the user to enter the temperature), and JButton (to convert the temperature from Celsius to Fahrenheit.) Future additions to this lesson may expand to cover all of the components shown above, but for now we will keep things simple by focusing on just these three.

The Design Area

The Design Area is where you will visually arrange your components after dragging them from the Palette. It has two views: source view, and design view. Design view is the default, as shown below in Figure 10. You can toggle between views at any time by clicking their respective tabs at the top of the window.


Figure 10: The Design Area, Design View (Click to Enlarge)

The figure above shows a single JFrame object, which is represented by the large blue shaded rectangle. Commonly expected behavior (such as quitting when the user clicks the "close" button) is auto-generated by the IDE and appears in the source view within uneditable blue sections of code called guarded blocks.


Figure 11: Generated Source Code (Click to Enlarge)

You may be surprised at the amount of code that has already been generated. Taking a look at the source view reveals that the IDE has created a private method named initComponents, which initializes the various components of the GUI. It tells the application to "exit on close", performs some layout-specific tasks, then packs the (soon to be added) components together on screen.

To learn how to code these components by hand, see: How to Make Frames (Main Windows) and Laying Out Components Within a Container.

The Property Editor

The Property Editor does what its name implies: it allows you to edit the properties of any given component. The Property Editor is intuitive to use; in it you will see a series of rows — one row per property — that you can click and edit without ever touching the source code. The following screenshot shows the Property Editor for our newly added JFrame object:


Figure 12: The Property Editor (Click to Enlarge)

After you've complete this lesson, feel free to return to the Property Editor to experiment with the various components that we have used.

The Inspector

The last component of the NetBeans IDE that we will use in this lesson is the Inspector:


Figure 13: The Inspector

The Inspector provides a graphical representation of your application's components. We will use the Inspector only once, to change a few variable names to something other than their defaults.

Creating the CelsiusConverter GUI

This section explains how to use the NetBeans IDE to create the CelsiusConverter GUI. As you drag each component from the Palette to the Design Area, the IDE will auto-generate the appropriate source code.

Step 1: Set the Title

First, set the title of the application's JFrame to "Celsius Converter", as previously shown in Figure 1.

To do so, single-click the JFrame in the Inspector:


Figure 14: Selecting the JFrame

Then, set its title with the Property Editor:


Figure 15: Setting the Title

You can set the title by either double-clicking the title property and entering the new text directly, or by clicking the button and entering the title in the provided field.

Step 2: Add a JTextField

Next, drag a JTextField from the Palette to the upper left corner of the Design Area. As you approach the upper left corner, the GUI builder will will provide visual cues (dashed lines) that suggest the appropriate spacing. Using these cues as a guide, drop a JTextField into the upper left hand corner of the window as shown below:


Figure 16: Adding the first JTextField (Click to Enlarge)

You may be tempted to erase the default text "JTextField1", but just leave it in place for now; we will replace it later in this lesson as we make the final adjustments to each component.

To learn how to code this component by hand, see How to Use Text Fields.

Step 3: Add a JLabel

Next, drag a JLabel onto the Design Area. Place it to the right of the JTextField, again watching for visual cues that suggest an appropriate amount of spacing. Make sure that text base for this component is aligned with that of the JTextField; the visual cues provided by the IDE should make this easy to determine.


Figure 17: Adding the JLabel (Click to Enlarge)

To learn how to code this component by hand, see How to Use Labels.

Step 4: Add a JButton

Next, drag a JButton from the Palette and position it to the left and underneath the JTextField. Again, the visual cues will help guide it into place.


Figure 18: Adding the JButton (Click to Enlarge)

You may be tempted to manually adjust the width of the JButton and JTextField, but just leave them as they are for now. You will learn how to correctly adjust these components later in this lesson under Adjusting the GUI Components.

To learn how to code this component by hand, see How to Use Buttons.

Step 5: Add a Second JLabel


Figure 19: Adding a second JLabel (Click to Enlarge)

Finally, add a second JLabel, repeating the process in step 2. Place this second label to the right of the JButton, as shown above in Figure 19.

Adjusting the GUI Components

With the GUI components now in place, it is time to make the final adjustments. There are a few different ways to do this; the order suggested here is just one possible approach.

Step 1: Set the Component Text

First, double-click the JTextField and JButton to remove or replace the default text that was inserted by the IDE. When you erase the text from the JTextField, it will shrink in size as shown below in Figure 20. Change the text of the JButton from "JButton1" to "Convert." Also make sure to change the top JLabel text to "Celsius" and the bottom to "Fahrenheit."


Figure 20: Setting the Component Text (Click to Enlarge)

Step 2: Set the Component Size

Next, shift-click the JTextField and JButton components; this will highlight each showing that they are selected. Right-click (control-click for mac users) Same Size -> Same Width. The components will now be the same width, as shown below in Figure 21. When you perform this step, make sure that JFrame itself is not also selected. If it is, the Same Size menu will not be active.


Figure 21: Setting the JTextField and JButton sizes (Click to Enlarge)

Step 3: Remove Extra Space

Finally, grab the lower right-hand corner of the JFrame and adjust its size to eliminate any extra whitespace. Note that if you eliminate all of the extra space (as shown below) the title (which only appears at runtime) may not show completely. The end-user is free to resize the application as desired, but you may want to leave some extra space on the right side to make sure that everything fits correctly. Experiment, and use the screenshot of the finished GUI (Figure 1) as a guideline.


Figure 22: The Completed GUI (Click to Enlarge)

The GUI portion of this application is now complete. If the NetBeans IDE has done its job right, you should feel that constructing this GUI was a simple, if not trivial, task. But take a minute to click on the Source tab; you might be surprised at the amount of code that has been generated.


Figure 23: The Generated Source Code (Click to Enlarge)

Figure 23 above shows a partial listing of the generated source code. To see the code in its entirety, click on the source tab and scroll up and down as necessary. You can expand or collapse certain blocks of code (such as method bodies) by clicking the + or - symbol on the left-hand side of the source editor.

Adding the Application Logic

So far, you have successfully created the GUI for the CelsiusConverter application. It is now time to add in the application logic. The following code is all that is necessary to convert a temperature from Celsius to Fahrenheit:
    //Parse degrees Celsius as a double and convert to Fahrenheit.
    int tempFahr = (int)((Double.parseDouble(tempTextField.getText())) 
	    * 1.8 + 32);
    fahrenheitLabel.setText(tempFahr + " Fahrenheit");
Completing this application is mostly a matter of pasting the above code into the correct location within the source code. There are, however, a couple of minor actions that you must also take before this will actually work. They are: change the default variable names, register the event listeners, and add the temperature conversion code.

Step 1: Change the Default Variable Names

Figure 24 below shows the default variable names as they currently appear within the Inspector. For each component, the variable name appears first, followed by the object's type in square brackets. For example, jTextField1 [JTextField] means that "jTextField1" is the variable name and "JTextField" is its type.


Figure 24: Default Variable Names

The default names are not very relevant in the context of this application, so it makes sense to change them from their defaults to something more meaningful. Right-click each variable name and choose "Change variable name." When you are finished, the variable names should appear as follows:


Figure 25: Changed Variable Names

The new variable names are "tempTextField", "celsiusLabel", "convertButton", and "fahrenheitLabel." Each change that you make in the Inspector will automatically propagate its way into the source code. You can rest assured that compilation will not fail due to typos or mistakes of that nature — mistakes that are common when editing by hand.

Step 2: Register the Event Listeners

When an end-user interacts with a Swing GUI component (such as clicking the Convert button), that component will generate a special kind of object (called an event object) and will broadcast it to any other objects that have previously registered themselves as listeners. If we were coding this application by hand, there would be a few additional steps to register an event listener on the Convert button. The NetBeans IDE, however, makes this process extremely simple:


Figure 26: Registering an Event Listener (Click to Enlarge)

In the Design Area, click on the Convert button to select it. Make sure that only the Convert button is selected (if the JFrame itself is also selected, this step will not work.) Right-click the Convert button and choose Events -> Action -> ActionPerformed. This will generate the required event-handling code, leaving you with empty method bodies in which to add your own functionality:


Figure 27: Empty Listener Method Body (Click to Enlarge)

There are many different event types to represent the various kinds of actions an end-user can take (clicking the mouse triggers one type of event, typing at the keyboard triggers another, moving the mouse yet another, and so on.) Our application is only concerned with the ActionEvent; for more information about event handling, see Writing Event Listeners.

Step 3: Add the Temperature Conversion Code

The final step is to simply paste the temperature conversion code into the empty method body:


Figure 28: Complete Listener Method Body (Click to Enlarge)

With the conversion code now in place, the application is complete. All that remains is to go ahead and actually run the program.

Step 4: Run the Application

Running the application is simply a matter of choosing Run -> Run Main Project. The first time you run this application, you will be prompted with a dialog asking to set CelsiusConverterGUI as the main class for this project. Click the OK button, and when the program finishes compiling, you should see the application running in its own window. You can run this program at any time using this same technique.

Congratulations! You have completed your first Swing application!

Comments:

Pretty cool, Scott. But you preserved that obsolete code from the old version. Double.parseDouble assumes everybody formats their number U.S. style. Rather chauvinistic. You should convert to an API, such as Scanner, that is more international.

Posted by Isaac on March 01, 2007 at 09:17 PM PST #

One problem when explaining concepts with IDE's like NetBeans, it often tends to hide lots of things otherwise simplifying work. Great to see you have added enough reference then and there, like Writing Event Listeners so that a novice user can go through it if they don't understand/know concepts completely.

Posted by Manikanda kumar on March 01, 2007 at 10:12 PM PST #

Nice work Scott. It might be worth to mention that the GUI editor offers a preview function. Using it, one might get an idea of what the GUI will look like in the end.

Posted by Benny on March 02, 2007 at 02:01 AM PST #

Isaac and Benny: Great suggestions, I have added them to my to-do list. Manikanda: Yes, hiding things and simplifying work is exactly the point. We can use tools like this to generate all of the GUI code, which can be incredibly time-consuming to write by hand in larger applications. The benefits of using the GUI builder become more and more apparent as the GUI requirements grow in complexity.

Posted by Scott Hommel on March 02, 2007 at 06:50 AM PST #

Have you consider to make a flash demo of this? When you tried to show something about an IDE, I think it's better to see it dynamic, no just images. I'm thinking in something like "see it in action" link in the article. You might work with the Netbeans team for something like that. Greetings, Osman Tegucigalpa, Honduras

Posted by Osman Santos on March 02, 2007 at 11:07 AM PST #

Osman: We may add flash to it in the future. I guess the bigger question here is, does everyone think this sort of information is useful? Would you like to see more examples added to this lesson? It might be nice to have enough examples to demonstrate all of the components in the Palette.

Posted by Scott Hommel on March 02, 2007 at 04:25 PM PST #

Very nice idea, but like Osman, I believe the utility to beginning users would be greatly improved by producing dynamic examples (eg, Flash).

Having the student run the project after each stage would also provide some interesting feedback to them.

And thanks, Isaac, for pointing out that parseDouble doesn't pay attention to locale. I hadn't realized that.

And I think you should make explicit who this is for - if this is their first NetBeans project, you've got to say a lot more about some of initial dialog steps.

Posted by Fred Swartz on March 03, 2007 at 03:30 PM PST #

Hi Fred, This lesson picks up after the "Getting Started with NetBeans IDE" lesson... there's a link to it in the first paragraph, plus a note that you should read that lesson first. Your comment also reminded me that I should add in how to use the preview button (the one that looks like an eye)

Posted by Scott Hommel on March 04, 2007 at 05:23 PM PST #

Thanks, I liked it and I'd like to see more. This actually was my first swing app. Here are a few things I noticed. Do with them as you will. 1. Please remove all of the "if you were hand-coding ... " stuff, or possibly move it to an appendix that provides references to examples, docs, and howto for hand-coding. We want to know how to do it right, with NB. :-) 2. Copy all of the external references to an appendix at the end. Then we have one set of links to "introduction", "writing event handlers", hand-coding frames" and so forth all in one place. Might even be able to get them out of tutorial body. 3. I want *MORE*! This is a trivial application, with a single button-driven form. I want to know how to have my form pop up another form (say a file chooser, so the user can select a file to load), how to set up an activate a menu, when and where to use different kinds of panes, and so on.

Posted by Richard Johnson on March 05, 2007 at 09:28 AM PST #

One more comment on the tutorial:

Please don't even mention the actual conversion logic until it's time to stick it in -- with the event handler. Where you have it is nice to know but kind of in the way of the overall flow of learning the IDE and swing, where it is now. (Besides, scrolling back through the text to get it to cut and paste was a bit of a pain.) :-)

Comments on previous comments:

1. Flash is probably a great marketing tool, but doesn't help a new NB / swing user (like me) actually _learn_ what to do. Better to leave it (IMO) so we have to go through the motions.

2. The preview function is good. I didn't think failing to mention it was an oversight, but rather a case of version skew, where the author had a less-recent version of NB than I did. It is an extremely useful thing.

3. Images of things we novices should not be expected to know make sense (for example finding something when right-clicked, or using the properties editor) but pictures of yet another menu, or detailed instructions of how to start a project tend to get in the way. (We can always go back to the intro.) I'd still be happy without flash.

Posted by Richard Johnson on March 05, 2007 at 09:41 AM PST #

Great feedback Richard! Yes, this first example is trivial. The idea is that as we move forward, we would write more and more complex applications with it. Ideally we would show all of the GUI components provided by the Palette.

Posted by Scott Hommel on March 05, 2007 at 02:56 PM PST #

IDE is defiantly good tool for rapid development of application but it add lot of obscure code from novice user's perspective. Take the case of event handling..If you do hand coding you will follow three required step..implementing concerned interface, Registering listener component and putting action code in abstract method body of interface. Now if you look at the auto generated code of IDE for event handling there is lot of gap which need explanation - hard to find! Is it possible to explain such thing in tutorial ?

Posted by Manoj Mistry on March 07, 2007 at 11:24 AM PST #

Hi Manoj, thanks for your feedback. This is a new issue for us on the tutorial team: does the NB auto-generated code even really need to be explained? It seems to me that the whole point of using the GUI builder is so that you don't have to think about the underlying GUI code. You are instead free to focus your programming efforts entirely on the application logic. If NB generates excess code I don't think we would explain/justify why in the tutorial; you would just have to accept the code that NB gives you. Users who *do* want to learn the underlying details should follow the provided links to the other lessons where they can learn core concepts. We are trying to walk a fine line here of showing users the quickest and easiest way (which would be using the NB GUI builder) but still provide lower-level discussions (in other lessons) for those who want to learn it from scratch.

Posted by Scott Hommel on March 07, 2007 at 04:57 PM PST #

I'm a first time user.. and helped a GREAT deal.. thanks alot.. please keep on with more of these.. thanks again.

Posted by jaco on March 13, 2007 at 08:09 AM PDT #

what I meant with my above post.. is that this tutorial helped a great deal.. .. oops .. forgot the preview first!

Posted by jaco on March 13, 2007 at 08:10 AM PDT #

What a great tutorial to start with NET Beans !. I have been looking around since long for a nice tutorial to start with my Java Project. Thanks ! Where can I find other tutorials of this series??

Posted by Penuel on April 16, 2007 at 10:50 AM PDT #

Hey Scott! Did you see the MS Step by Step series of books? It would be rally good to have something like that in Java too! Step by Step is proven to be most successful.

Posted by Faisal on April 17, 2007 at 01:34 PM PDT #

I'm really glad to hear that everyone likes this approach. This is currently our only tutorial of this style, but I'm sure we'll be writing more in the near future. Ideally I'd like to write enough of these NB tutorials to cover every Swing component in the Palette. Feel free to post comments on what components you'd like to see covered in the next one!

Posted by Scott Hommel on April 22, 2007 at 09:13 PM PDT #

I like the idea of flash demo (or JavaFX script) Netbeans.org uses this type of media pretty often with good result!

Posted by Bob on May 22, 2007 at 12:42 PM PDT #

i was having trouble with a java program i was trying to create. i was trying to create a temperature conversion program for celcius to faranheit and vice versa without a GUI. could someone email me a code example

Posted by John Matthews on October 08, 2007 at 09:29 AM PDT #

Thank you very much for your tutorial. I find that is it very useful to me.

Posted by Melvin on August 13, 2009 at 06:50 PM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed

« December 2009
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today

Feeds

Search this blog

Links

Weblog menu

Today's referrers

Today's Page Hits: 173