FeaturesPluginsDocs & SupportCommunityPartners

GUI Building in NetBeans IDE 4.0

This short tutorial guides you through the process of creating an application called ColorSwitcher. You will build a simple program that enables you to switch the color of a panel from light gray to medium gray to black.

During the process of creating ColorSwitcher, you will learn how to:

Getting Started

In the IDE, all Java development takes place within projects. An IDE project is a group of Java source files plus its associated meta data, including project-specific properties files, an Ant build script that controls the build and run settings, and a project.xml file that maps Ant targets to IDE commands.

Creating a Project

First we need to create the ColorSwitcher Java application, but to do this we need to create a new project within which to store sources and other project files. While Java applications are often comprised of several IDE projects, for the purposes of this tutorial we will build a simple application which is stored entirely in a single project.

To create a new ColorSwitcher application project:

  1. Choose File Tip New Project (Ctrl+Shift+N). Alternately, you can click the New Project icon in the IDE toolbar.

  2. In the Categories pane, select the General folder. In the Projects pane, choose Java Application and click Next.

  3. Enter ColorSwitcher in the Project Name field and specify the project location.

  4. Ensure the Set as Main Project checkbox is selected and deselect Create Main Class if it is selected.

  5. Click Finish.

    The IDE creates the ColorSwitcher folder on your system in the designated location. This folder contains all the project's associated files, including its Ant script, folders for storing sources and tests, as well as a folder for project-specific metadata. You can view this structure using the Files window.

Creating a Container

In order to proceed with developing our application, we need to create a Java container within which we will place the other required GUI components. After creating the new application, you may have noticed that the Source Packages folder in the Projects window contains an empty <default package> node. Now we'll create a container using the JFrame component and place the container in a new package.

To create a JFrame container:

  1. In the Projects window, right-click the ColorSwitcher node and choose New Tip JFrame Form.

  2. Enter ColorSwitch as the Class Name.

  3. Enter my.colorswitcher.pkg as the Package.

  4. Click Finish.

    The IDE creates the ColorSwitch form and the ColorSwitch class within the ColorSwitch.java application. The my.colorswitcher.pkg package replaces the <default package> and the ColorSwitcher form opens in the Editor window in Design view.

Defining the Project's Main Class

Before proceding any further, we need to let the IDE know which class is the Main Class so that build and run commands will work properly. You can set any class with a main method as the Main Class, but in this case we want to set the ColorSwitcher class we created in the previous step as the Main Class.

To set the Main Class

  1. In the Project window, right-click the ColorSwitcher project node and choose Properties.

  2. In the left pane, select Running Project under the Run node.

  3. In the right pane, click the Browse button to the right of the Main Class field.

  4. In the Browse Main Classes dialogue that appears, select my.colorswitcher.pkg.ColorSwitch and click Select Main Class.

  5. Click OK to exit the Project Properties dialogue.

    The IDE sets the main class parameter that it references when executing build and run commands.

Getting Familiar with the IDE's Editor

Now that we've setup a new project for our application, let's take a minute to familiarize ourselves with the IDE's Editor interface. Below is a screengrab of our ColorSwitcher application open in the IDE's Editor Design view.

The IDE's GUI Editor Interface.

When we added the JFrame container, the IDE opened the newly-created ColorSwitch form in an editor tab with a toolbar containing Source and Design toggle buttons. These buttons enable you to choose between viewing the ColorSwitch class's source code or a graphical view of its GUI components.

Initially, the ColorSwitch class opened in Design view with the following three windows automatically docked along the IDE's right edge:

  • Palette. Contains tabs for various JFC/Swing, AWT, and JavaBeans components, along with a selection of layout managers.
  • Inspector. Provides a representation of all the components, both visual and non-visual, in your application as a tree hierarchy. The Inspector also provides visual feedback about what component in the tree is currently being edited in the Editor as well as allows you to organize components in the available panels.
  • Properties. Displays the properties of the component currently selected in the Inspector, Editor, Projects or Files windows.

Clicking the Source button displays the application's Java source code with sections of code generated by the IDE indicated by blue Guarded Blocks which are not editable in Source view. You can type only in the white areas of the Editor when in Source view. Clicking the Design button returns the IDE's Editor to the graphical view.

Editing the Form

Now that you have created a form and have had a chance to familiarize yourself with the IDE's GUI tools, it's time to begin developing the nuts and bolts of our GUI application. In this step we'll change the JFrame's default layout, add the necessary GUI elements to the form using the IDE's Palette, and rearrange them using the GridBag Customizer.

Selecting a Layout Manager

Now that we've added a JFrame as our form's top-level container, the next step is to specify the Layout Manager we want to use to control the size and position of the components within the container. Each container type has a default layout manager. The default layout manager for the JFrame component is BorderLayout which divides the container into five sections (north, south, east, west, and center).

the Palette's Layout tab

In this step, we'll switch to the GridBagLayout layout manager, which provides precise control over all aspects of the layout using a complex set of component properties called "constraints." The GridBagLayout places components in a grid of rows and columns in which grid cells do not all have to be the same size. In addition, components can span multiple rows, columns, or both.





To change layout managers:

  1. In the Palette, click the Layouts tab to access the available layout managers in the Java Foundation Classes (JFC). Note that when you mouse over layout icons in the Palette, a tool tip appears to display the name of the layout manager.

  2. Click the GridBagLayout button (Tip) in the Layouts tab.

  3. Click anywhere on the grey ColorSwitch form in the Editor to set the layout manager.

    The GridBagLayout is added to the JFrame's component hierarchy in the Inspector.

Adding a Button

Now that we've changed the layout manager, we need to add the button that will actually operate the ColorSwitcher application. Notice the IDE's "pick & drop" behavior when accomplishing this.

To add a button:

  1. In the Swing palette, select the JButton component.

  2. Click anywhere on the ColorSwitch form in the Editor to add the JButton component to the form.

    The JButton component is displayed in the Editor in Design view and its corresponding node is displayed in the Inspector. The JButton component's source code is added to the source code and is visible in Source view.

Now edit the button so that it will display the correct text in the desired font style and size.

To rename the button and change its display font:

  1. In the Editor's Design view, right-click the JButton component and select Edit Text from the contextual menu. Alternately, you can simply click the button and push the spacebar.

  2. Enter Switch Color in the text field. Press Enter.

  3. With the JButton component still selected, scroll to the font property in the Properties window and click the ellipsis (...) button.

  4. In the Font Editor dialog, select Bold for font style and 14 for font size. Click OK.

    The JButton component label Switch Color appears in larger bold type.

The Editor displays the Switch Color button centered in its JFrame container, delineated by a dark purple border. The remainder of the form should be empty gray space with a light blue boundary line indicating the edge of the JFrame itself.

Adding a Label

Since our application uses a label to display the colors the button will call, we need to add the label next. In this step we'll select the JLabel Swing component from the IDE's Palette and place it in the form in the Editor's workspace. Again, notice the IDE's "pick & drop" behavior when accomplishing this.

To add a label component:

  1. In the Palette window, click the Swing tab to display the available Swing components.

  2. Select the JLabel component.

  3. Click anywhere on the ColorSwitch form in the Editor to add the JLabel component to the form.

    A label with the text jLabel1 is displayed in the Editor and a node named jLabel1 [JLabel] is displayed and highlighted in the Inspector's tree view. In addition, the JLabel component's properties are displayed in the Properties window and its source code is added in the Editor's Source view.

Using the GridBag Customizer to Adjust the Layout

Unlike other Layouts, the GridBagLayout displays no properties in the Properties window when selected the Inspector. The GridBag Customizer enables you to visually adjust the placement and constraints of components in a GridBagLayout. It includes a property sheet for GridBag constraints, buttons for adjusting the constraints, and a rough depiction of the layout of the components.

To adjust the form's layout using the GridBag Customizer:

  1. To open the GridBag Customizer, right-click the GridBagLayout node in the Inspector and choose Customize.

  2. In the workspace area (the window's right pane), reposition the JButton by clicking its center and dragging it below the JLabel component. As you drag the button, a black and red grid indicates the positions available. Notice also its Grid X and Grid Y properties in the left pane change to reflect its new position.

  3. Select the JLabel component and adjust the JLabel's Internal Padding Y constraint to 33, so that the label completely fills the cell above the button. Then set its Fill constraint to Horizontal.

  4. Once the approximate layout of the components has been established, control-select the JLabel and the JButton and set the Insets (left, right, top and bottom) for both to 5 to increase the space between the components. The GridBag Customizer displays the inset with light yellow margins around the components.

  5. Click Close to exit the GridBag Customizer.
  6. The IDE updates the edited components to reflect their new positioning and other constraints. Although the Editor's Design view does not display a grid, it now contains a single column and two rows.

The GridBag Customizer - click for fullsize

Though the GridBag Customizer is where you actually edit the form when using the GridBag layout, the Editor's Design view more closely reflects how the components will look at runtime. Often, it is helpful to sketch out the way you want your layout to look before you using the GridBag Customizer.

Making the Final Adjustments to the Form

Now that we've arranged the two components in our form, we need to edit the label so that it will display the color when activated by the Color Switcher button. We'll do this by removing the label's text and altering its opacity property so that it will only display the color when the button is clicked.

To edit the label's properties:

  1. In the Editor's Design view, select the JLabel component.

  2. In the Properties window, display the component's properties by clicking the Properties button.

  3. Scroll to the text property, select the current jLabel1 name, and delete the text leaving the text field blank. Press Enter.

  4. Scroll down to Other Properties, select the checkbox for the opaque property, and press Enter again.
  5. The jLabel1 component disappears from the Editor workspace, however, it is still selectable via its corresponding node in the Inspector.

Finally, we need to adjust our form's properties so that it will display in an appropriately sized window when we run it.

To edit the form's properties:

  1. In the Editor's Design view, select the JFrame container in the Inspector and choose the Code button.

  2. In the Properties window, scroll to the Generate Resize Code option and set it to True. Press Enter.

  3. Scroll to the Form Size property, set the size to [200, 150], and press Enter.
  4. Whenever you run the application, the form will be generated in a window with the new dimensions.

Setting Component Events

Now that you have created the necessary components and added them to our application's form, we need to establish the interactivity between them and the user. There are several ways to do this, but for the purposes of this tutorial we'll focus on using the Editor's Source view to enter the code directly.

Setting Up the Button

The first thing we need to do is set up the button to switch color. In this step we'll add the method for the user input we want and the listener code and that will watch for it.

To add the mouse event:

  1. Place focus in the Editor window (in Design view), if it's not already.
  2. Right-click the jButton1 component and choose Events Tip Mouse Tip MouseClicked.

    The IDE generates the listener code jButton1.addMouseListener and event method jButton1MouseClicked(). The focus switches to Source view containing the Java source code for the ColorSwitcher class and the cursor is placed on the line where we'll add the event handling code in the following step.


Tip Guarded blocks of Java code generated by the IDE have a light blue background and cannot be edited directly in the Source view. To edit code within a guarded block, click the Design button to return to Design view.

Adding Event Handler Code

Once the jButton1MouseClicked() method has been created, you can add custom code for handling this event when it occurs. The goal is that each click of the Switch Color button will change the color of the label.

To add the code:

  1. In the Editor toolbar, locate the Quick Browse combo box (immediately to the right of the Design toggle button) and select JButton1 from the list of your ColorSwitcher application's elements. The cursor appears at the beginning of the JButton1 variable declaration in the JButton1's blue guarded block.

  2. Move the cursor to the line below the variable declaration section (on or about line 67).
  3. Tip You can display line numbers in Editor's Source view by right-clicking in the left margin and choosing Show Line Numbers.

  4. Declare the following new variable:
    private java.awt.Color currentColor = java.awt.Color.lightGray;
  5. In the Quick Browse combo box, select jButton1MouseClicked. Place the cursor after //Add your handling code here: below the guarded block (on or about line 50) and type the following:
    if (currentColor == java.awt.Color.lightGray)
        currentColor = java.awt.Color.gray;
    else if (currentColor == java.awt.Color.gray)
        currentColor = java.awt.Color.black;
    else
        currentColor = java.awt.Color.lightGray;
    jLabel1.setBackground (currentColor);
        
    Tip Note that the last line is jLabel with the number one ("1") preceeding the period and not the letter "l".

  6. Save the file by choosing File Tip Save (Ctrl + S).

    The IDE stores your code and places an error icon to the left of any line where it finds a problem.

The IDE's Editor in Source view - click for fullsize

As you work you can preview the form by clicking the Test Form button in the Editor's toolbar. The form opens in its own window, allowing you to test it prior to buliding and running.

Adding GUI Components with the Palette Manager

If you work with custom components, beans, or component libraries, you can add them to the IDE's palette with the Palette Manager, pictured below. To launch the Palette Manager, choose Tools Tip Palette Manager.

GUI Editor interface

Seeing the ColorSwitcher Application in Action

Now that you have successfully built the ColorSwitcher form, you can try your application to see the results.

Compiling and Running Your Program

Now that we've created the user interface and the connections between the components, you can compile and run your application.

To compile the program:

  1. Compile ColorSwitcher by choosing Build Tip Compile (F9).

    The Output window opens to display the progress and any errors that occur. If the build is successful, the "Finished ColorSwitcher" message appears in the status bar at the bottom of the main window.

If there are problems with the build, error messages are displayed in the Output window. You can double-click an error message to jump to the line in the source code where the error occurred. Once the build is successful, you can run the application.

Tip Alternately, you can skip the build step and simply run your program. The IDE will compile any classes that are out of date automatically before running the program.

To run the program:

  1. Run the ColorSwitcher application by choosing Run Tip Run Other Tip Run Main Project (F6).

    IDE displays the Output window. If there are execution errors, the IDE displays both the Output and Execution windows.


When the run command is successful, the ColorSwitcher application is displayed and should appear as in the image below. In the application window, click the Switch Color button to check that the area above the button changes color. Each time you click the button, the label above the button should change from light gray to medium gray to black. When you are finished testing your application, exit the application by clicking the closing the window.
The ColorSwitch after the first click.

For Further Investigation

You have now completed the IDE's GUI Building tutorial. For more information on using NetBeans IDE, see:

  • NetBeans Online Help. The documentation included in NetBeans IDE itself. Press F1 to open the online help.
  • Using NetBeans IDE. The complete guide to developing Java applications in NetBeans IDE.
  • NetBeans Support and Docs. Full list of articles, FAQs, and mailing lists for NetBeans IDE users.

Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by