Skip Headers
NetBeans Developing Applications with NetBeans IDE
Release 8.0

E50452-06
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

10 Implementing Java GUIs

This chapter describes how to implement Java GUIs using the IDE's Java GUI tools.

10.1 About Implementing Java GUIs

In Java applications, the components that comprise a GUI (Graphical User Interface) are stored in containers called forms. The Java language provides a set of user interface components from which GUI forms can be built.

The IDE's GUI Builder assists you in designing and building Java forms by providing a series of tools that simplify the process.

10.1.1 The IDE's Java GUI Tools

The IDE provides several tools to simplify the process of building GUIs:

  • GUI Builder. The primary workspace within which GUI design takes place in the IDE. The GUI Builder enables you to lay out forms by placing components where you want them and by providing visual feedback in the form of guidelines. See Section 10.2, "Working with the GUI Builder."

  • Navigator window. Displays a tree hierarchy of all components contained in the currently opened form. Displayed items include visual components and containers, such as buttons, labels, menus, and panels, as well as non-visual components such as timers and data sources.

  • Palette window. A list containing all the components that can be added to forms. You can customize the window to display its contents as icons only, or as icons with component names.

  • Properties window. Displays the editable settings for the currently selected component.

  • Connection wizard. Assists in setting events between components in a form without the need of writing code manually.

  • Manager. Enables you to add, remove, and organize window components such as Swing components, AWT components, Layouts, and beans.

In addition, the IDE provides support for the Beans Binding specification which provides a way to synchronize the values of different bean properties. This support also simplifies the creation of desktop database applications.

To access binding features, right-click a component, select Bind in the context menu, and select a property from the drop-down list. For more information see "Working with Database Applications and Beans Binding."

For more information about creating Java GUIs, see the Java GUI Application Learning Trail at:

https://netbeans.org/kb/trails/matisse.html

For more information about handling events in your application, see the Creating a GUI with JFC/Swing tutorial at:

http://docs.oracle.com/javase/tutorial/uiswing/

10.2 Working with the GUI Builder

The GUI Builder is a tool for designing GUIs visually. As you create and modify your GUI, the IDE automatically generates the Java code to implement the interface. GUI forms are indicated by form nodes (form node icon) in the Projects, Files, and Favorites windows.

When you open a GUI form, the IDE displays it in an Editor tab with toggle buttons that enable switching between Source and Design views. The Design view enables you to work with GUI forms visually while the Source view permits the form's source code to be edited directly. Each time you select a form's Design toggle button, the Palette, Navigator, and Properties windows appear automatically.

Components are typically added to a form using the window and arranged in the GUI Builder workspace. As you work, the GUI Builder automatically displays guidelines suggesting preferred alignment and anchoring for the components you add. Use the Navigator window in conjunction with the Properties window to examine a form's component and layout manager properties, manage component event handlers, and define how code is generated.

Note:

Interfaces created with the GroupLayout layout manager must have the Swing Layout Extensions library available if they are run outside the IDE. The Swing Layout Extension Library is included in the Java Platform JDK 6 or higher, so no additional steps are needed if you develop the application with JDK 6 or 7 and deploy in environments that have JRE version 6 or higher. For more information, see Section 10.6, "Deploying GUI Applications."

To design GUI applications:

These are the basic steps to create and deploy GUI applications:

  1. Create forms. Forms can be created within existing projects. To simplify handling, a form includes containers, subcontainers, and components. Layout managers control the arrangement of components within a container. You also have the option to create a Multiple Document Interface (MDI) application.

  2. Edit forms. A component within a form has behavior, appearance, and accessibility properties that can be modified directly or through the property editor. See Section 10.2.10, "How to Manage Component Events" and Section 10.3.1, "How to Set the Layout Manager."

  3. Preview forms. With the Preview Design capability you can test your form without compiling or running it. See Section 10.2.14, "How to Preview a Form."

  4. Deploy the GUI application. Applications are typically distributed as JAR files. Before deployment you must ensure that the JAR contains all necessary libraries. See Section 10.6, "Deploying GUI Applications."

10.2.1 How to Create a New Form

In the IDE you can create JFC/Swing or AWT (Abstract Window Toolkit) forms, pre-built sample application skeletons, or any class that is based on the JavaBeans component architecture using the provided templates.

Note:

The GUI Builder cannot be used to edit GUI forms that were created outside of the IDE.

To create a new GUI form in an existing project:

  1. Choose File > New File from the main menu.

  2. In the New wizard's Project combo box, select the project for which you want to create the form.

  3. Expand the Swing GUI Forms or AWT GUI forms node in the Categories pane and select the desired form template. Click Next.

  4. Enter the GUI form's class name and location. Click Finish.

    The IDE creates a blank form of the selected type and opens the form in the Source Editor's Design view.

Note:

In order to avoid repaint problems at both design and run time, only AWT components should be used in AWT forms and only JFC/Swing components should be used in JFC/Swing forms.

GUI Form Types in the New File Wizard:

The following table lists the types of form templates available in the IDE. Each differs in the design time and run time look of the form, as well as in the code generated for the form's class.

Table 10-1 GUI Form Types

Form Type Description

JApplet

Program run by a Java-enabled web browser or other applet viewer.

JDialog

Modal or modeless window for collecting user input.

JFrame

Top-level application window.

JInternalFrame

An internal frame that can be placed on a JDesktopPane component to create an MDI application.

JPanel

Lightweight container for holding parts of an interface. In turn, the container can be used in any other container, such as a JFrame, JPanel, JApplet, or JDialog component.

Bean Form

The template used to create a new form based on any JavaBeans component. The new form can be visual or nonvisual. In the New wizard go to the Superclass page and on the Form Superclass page specify the bean class. The bean class that you specify when creating the new form must be in the classpath and must be already compiled.

 

A bean is any class that complies with the JavaBeans component architecture. A bean must have a public constructor without parameters. Use any JFC/Swing component as an example of a JavaBeans class. For example, use javax.swing.JButton to create a form to produce a customized button.

 

To use this template to create a plain container for holding beans, specify java.lang.Object as the superclass.

AWT Forms

Visual forms that are based on the AWT. The AWT forms include Applet, Dialog, Frame, and Panel.

Sample Forms

Customized sample forms that include a JFrame-based application with three menus, a JFrame application that can be used as the main window for an MDI application, and a dialog box with OK and Cancel buttons.


10.2.2 How to Work with Containers

Java GUIs are forms comprised of top-level containers within which are grouped sub-containers as well as the various components used to provide the desired information and control functionality.

10.2.2.1 Controlling View Focus

It is often useful to focus work on single subcontainers rather than the entire form the GUI Builder generally displays. When working with large forms containing complex nested hierarchies of containers, changing the scope of the GUI Builder's focus enables you to concentrate on specific parts of your interface.

To change the GUI Builder's focus to a specific container:

In the GUI Builder or Navigator window, right-click the container you want to edit.

  • Choose Design This Container from the contextual menu.

  • The IDE adjusts the workspace display such that the current container fills the work area and hides the form's other components. The form's entire hierarchy remains available in the Navigator window.

To return the GUI Builder's display focus to the entire form:

  • Right-click the container in the GUI Builder.

  • Choose Design Top Container from the contextual menu.

    The IDE adjusts the work area display such that the entire form is visible. If the Design Top Container menu item is dimmed, you are already designing the entire form.

10.2.2.2 Reordering Components Within a Container

The component order in a container follows the sequence in which components are added. See Section 10.2.3, "How to Add a Component to a Form." If the layout manager for a container does not use constraints (FlowLayout, BoxLayout, and GridLayout), the order of components also determines how they are arranged visually. You can reorder the components in the Navigator window or drag the components in the form itself.

With layout managers that use constraints (BorderLayout, GridBagLayout, CardLayout, AbsoluteLayout, and Null Layout), the order of components in the container does not determine the order in which the components appear. For these containers, the component order can only be changed in the Navigator window. Although GridBagLayout uses constraints to determine how components are arranged, component order determines the layout when the Grid X and Grid Y constraints are not used. See Section 10.3, "Working with Layout Managers."

10.2.3 How to Add a Component to a Form

Once you have created a new form, you can add components to display information and control functionality. In the IDE, you can add components several ways, including:

  • Drag and Drop

  • Pick and Plop

  • The Navigator window.The IDE's Navigator window provides a hierarchical tree view of the form's various components. Each form is represented by a root node (Root node for a hierarchical tree icon within which all components in the form's class are contained. All other GUI components are organized into one of the following two subnodes:

    • Form Container node (Root node for a hierarchical tree icon). Represents the top level of the form's hierarchy and contains the visible components currently displayed in the GUI Builder.

    • Other Components node (icon representing other components node). Contains the form's non-visual components.

To add a component from the Palette:

  1. To select a component in the window click its icon. Without releasing the mouse button, drag the component to the desired location in the form. For more information, see Section 10.2.4, "How to Select Components in a Form."

  2. If you want to add the component to the Other Components node, drag the component to the white area outside the form in the GUI Editor's workspace.

The IDE adds the component to the selected container in the form.

To add multiple components from the Palette:

  1. Click a component icon.

  2. Shift+Click in the form to place the first component.

  3. Click all locations.

    If you want to add the component to the Other Components node, click in the white area outside the form in the GUI Editor's workspace.

The IDE adds the components to the selected container in the form.

To add a component using the Navigator window:

  1. In the Navigator window, right-click the container to which you want to add a component.

  2. Choose the desired component from the Add From submenu.

The IDE adds the component to the selected container in the form.

To add a bean from the Projects, Files, or Favorites windows:

  1. In the Files window, locate the bean's class node. The class must be a bean and it must be compiled.

    Note:

    For a class to be a bean, it must be possible to create an instance of the class using an empty public constructor.

  2. Right-click the class node and choose Copy from the contextual menu.

  3. Choose Paste from the contextual menu of either the GUI Builder or the Other Components node in the Navigator window.

The IDE adds the bean to the current form. See Section 10.4, "Adding a Bean to the Window."

Note:

When working with nested containers, it is sometimes difficult to select the container to which you want to add the component. You must first select the desired container before selecting the component you want to add. You then select the component from the window, hold down the Alt key, and click the desired container again to add the component.

10.2.4 How to Select Components in a Form

The IDE's GUI Builder and Navigator window always display the same selected component or components. Selecting a component in one window automatically selects it in the other.

To select a single component:

Click the component's node in the Navigator window or click the component in the GUI Builder.

To select multiple components, do one of the following:

  • Hold down the Control key while clicking multiple components in the Form Editor or while clicking multiple nodes in the Navigator window.

  • In the GUI Builder, hold down the Shift key while holding down the left mouse button and drag the mouse over each component in the group. A rectangle is painted as the mouse is dragged over the group of components. When the mouse button is released, all the components included in the rectangle are selected.

  • In the Navigator window, to select a consecutive group of components, Shift+click the first one, and while holding down the Shift key, click the last component in the group.

To select next and previous components:

Press Tab in the GUI Builder to select the next component or press Shift+Tab to select the previous component.

10.2.5 Controlling Selection Depth

When working with nested components (components within a container like a panel for example), clicking in the GUI Builder always selects the deepest component at the point of the click. You can, however, select nested components on different levels using modifier keys, as described below.

Right-click to display the contextual menu for the selected container or subcomponent. The right-click action does not change the selection depth.

To select the parent container of a selected component:

  1. Press and hold the Alt key.

  2. In the GUI Builder, click the selected component.

    If the currently selected component does not have a parent container (i.e. it is the container component for the entire form), Alt+Click selects the deepest component at the point of the click.

To select a subcomponent of a selected container:

  1. Press and hold both the Alt and Shift keys.

  2. Click the subcomponent.

    If the currently selected component does not contain any subcomponents, the container component for the entire form is selected.

Note:

It is often easier to select components using the Navigator window than the GUI Builder.

10.2.6 How to Align Components

Once you have added components to a form you can adjust the alignment.

To align components:

  1. Select the components you want to align in the GUI Builder's workspace.

  2. Click the appropriate align button in the GUI Builder toolbar. Alternately, you can right-click either component and choose Align > Left in Column (or Align > Right in Column) from the pop-up menu.

    The IDE shifts the component positions such that the specified edges are aligned and the component anchoring relationships are updated.

To align component baselines:

  1. Select the component you want to align in the GUI Builder's workspace.

  2. Drag the component to the right or left of the selected component.

  3. A horizontal guideline appears indicating that the selected component's baseline is aligned with the baseline of the second component and a vertical guideline suggest the spacing between the two components. Click to position the component.

    The IDE snaps the second component into a position aligned with the baseline of the first and displays status lines indicating the component spacing and anchoring relationships.

To indent components:

  1. Select the component you want to indent in the GUI Builder workspace.

  2. Select the component below the component below which you want to indent it.

  3. When guidelines appear indicating that the first component's left edge is aligned with that of the JLabel, move it further to the right until secondary indentation guidelines appear.

  4. Click to position the component.

    The IDE indents the second component below the first component.

For more information of working with components see Section 10.2.4, "How to Select Components in a Form," Section 10.2.7, "How to Size Components," and Section 10.2.8, "How to Edit Component Properties."

10.2.7 How to Size Components

It is often beneficial to set several related components, such as buttons in modal dialogs, to be the same size so they can be easily recognized as offering similar functionality. You can also adjust the resizing behavior of components to ensure that component relationships are maintained at runtime.

To set components to the same size:

  1. Select all of the components you want to resize in the GUI Builder's workspace.

  2. Right-click any one of components, and choose Set the Same Size > Set Width (or Same Size > Set Height) from the contextual menu.

    The IDE sets the selected components to the same size and adds small graphic to indicate the component relationships.

To set component resizing behavior:

  1. Select the components whose auto resizing behavior you want to set.

  2. Right-click any one of the components and choose Auto Resizing > Horizontal (or Auto Resizing > Vertical) from the pop-up menu.

    The IDE sets the components auto-resizing behavior to resize horizontally at runtime. The alignment guidelines and anchoring indicators are updated to indicate the new component relationships.

For more information of working with components see Section 10.2.4, "How to Select Components in a Form," Section 10.2.7, "How to Size Components," and Section 10.2.8, "How to Edit Component Properties."

10.2.8 How to Edit Component Properties

Once you have added a component to a form, you can edit values in the Properties window to modify its behavior and appearance.

To edit a component's properties:

  1. Select the component in the GUI Builder or Navigator window to display its properties in the Properties window.

    Note:

    If you select multiple components, their common properties are displayed and any modifications apply to all of the selected components.

  2. Click a button at the top of the Properties window to select an appropriate property.

  3. In the Properties window select the property and enter the desired value.

  4. (Optional) If the property you want to edit has an ellipsis (...) button, click it to open a special property editor where you can modify both the property and the initialization code generated for it.

  5. (Optional) If you are using the property editor, use the Select Mode combo box to choose between available custom editors for the property, make the necessary changes, and click OK.

    The IDE applies the new parameter values to the selected components.

To return a property to its default value:

Right-click the property name and choose Restore Default Value from the contextual menu. The IDE returns the selected to its default value.

Note:

You can edit text label properties for common components directly in the GUI Builder.

For more information of working with components see Section 10.2.10, "How to Manage Component Events,"Section 10.3.4, "How to Set Layout Properties," and Section 10.2.11, "How to Modify GUI Source Code."

10.2.9 How to Set Events with the Connection Wizard

Use the Connection wizard to set events between two components within a form without having to write code manually.

To set an event using the Connection wizard:

  1. Click the Connection Mode button (Connection Mode button) in the GUI Builder toolbar.

  2. In the GUI Builder or Navigator window, select the component that fires the event. Section 10.2, "Working with the GUI Builder."

    Note:

    The selected component is highlighted in red when selected.

  3. Select the component whose state you want to affect with the event.

    Note:

    The selected component is highlighted in red when selected.

  4. On the Connection wizard's Select Source Event page, expand the event type directory node and select the event that the trigger component fires from the Events list. Accept the default handler method name or type in a new name and click Next.

  5. On the Specify Target Operation page, specify the operation to be performed on the target component by selecting the appropriate radio button and choosing from the list of operations. Click Next.

    Note:

    If you choose a method call with no parameters, the wizard's Finish button becomes available.

  6. (Optional) If you wish to enter event handler code directly, click the User Code radio button and click Finish. The insertion point is placed in the new event handler in the Source Editor, where you can write the event handler code yourself. For more information see Section 10.2.10, "How to Manage Component Events."

  7. On the Enter Parameters page, specify the values for each tab's target property or method by selecting the source from which each parameter's value is acquired.

    The source code generated for each of the parameters is displayed in the Generated Parameters Preview field.

  8. Click Finish.

    The IDE automatically generates the code to connect the form's components.

10.2.10 How to Manage Component Events

The Java programming language uses events to enable GUI form behavior. Source objects can trigger events which one or more objects with event listeners react to by means of event handlers.

10.2.10.1 Defining Event Handlers

You can define event handlers using a component's property sheet or contextual menu. You can also define an event handler using the Connection wizard.

To define an event handler using the property sheet:

  1. Select the component in the Navigator window.

  2. Click the Events button at the top of the Properties window.

  3. Click the value of the desired event in the list. Initially, the value for all events is <none>. When you click the value field, <none> is automatically replaced with the default event name.

  4. Click the event's ellipsis (...) button to open the Handlers dialog box.

  5. Click the Add button to add a new name to the list of handlers. Click OK.

    The code for the listener and the empty handler method body is generated.

    Note:

    You still must add the desired code for the new event handler in the Source Editor.

To define an event handler using the contextual menu:

  1. Right-click a form component in the Files window, Project window, or Navigator window.

  2. Choose Events from the contextual menu and its submenus. Bold menu items in the Events submenus indicate event handlers that have already been defined.

    The code for the listener and the empty body of the handler method is generated. The default name is assigned to the event handler.

  3. Add your code for the new event handler in the Source Editor.

    Note:

    If multiple events are of the same type, you can use the same handler for all of them. For example, you could set both focusGained and focusLost to use the button1FocusChange handler since they are both of the type java.awt.event.FocusEvent. You can also use the same handler for the same event on multiple components.

    Note:

    You can set the code generation style for how the component event code is generated. Choose Tools > Options. Select the Miscellaneous pane and then select the GUI Builder tab. Set the Listener Generation Style property, one of Anonymous Innerclasses, One Innerclass, or Main Class.

To add multiple handlers for one event:

  1. In the Navigator window, select the component for which you want to add multiple handlers.

  2. Click the Events button at the top of the Properties window.

  3. Select the event in the property sheet and click the ellipsis (...) button to display the Handlers dialog box. Click the Add button and fill out the form. Repeat these steps to add additional event handlers.

To remove event handlers:

  1. In the Navigator window, select the component from which you want to remove the event handlers.

  2. Click the Events button at the top of the Properties window.

  3. Select the event in the property sheet and click the ellipsis (...) button to display the Handlers dialog box. Select the unwanted handler and click the Remove button.

    Alternately, go to the Properties window and delete the name of the handler you want to remove.

  4. In the Handlers dialog box, select the unwanted handler and click Remove.

When you remove an event handler, the corresponding code block is deleted. If more than one handler uses the same name and same block of code, deleting a single reference to the code does not delete the code itself. You must delete all references to delete the corresponding code block; a confirmation dialog box is displayed first.

For more information about how to handle events in your program, including information about the Java event model, see the Creating a GUI with JFC/Swing tutorial at:

http://docs.oracle.com/javase/tutorial/uiswing/

10.2.11 How to Modify GUI Source Code

The IDE automatically generates blue guarded blocks of code as you create your GUI form in the GUI Builder. Guarded text generated includes:

  • Blocks of components' variable declarations.

  • The initComponents() method, in which form initialization is performed. This method is called from the form's constructor and though it is not editable manually, to affect the way it is generated, edit the Code properties in the component's property sheet.The header (and trailing brace) of all event handlers.

You can modify the way initialization code is generated and even write custom code to be placed within the initialization code.

10.2.11.1 Modifying Code Generation for Form Components

You can modify the way initialization code is generated for a component, form, or component property by editing its Code properties in the Properties window. In addition, you can write custom code and specify where it should be placed within the initialization code.

To modify a form component's guarded block:

  1. In the Navigator window, select the component whose initialization code you want to edit.

  2. Click the Code button at the top of the Properties window to view the Code properties.

  3. Select the property you wish to edit and enter the desired value.

    The IDE updates the selected component's guarded code block with the new value.

Alternatively, you can customize code generated for a component through the Code Customizer dialog box. To open this dialog box, right-click a component in the Design view of the GUI Builder and choose Customize Code.

10.2.11.2 Setting Variable Modifiers for a Java Component

You can set the Java language modifiers for a Java element using the Variables Modifier Property Editor dialog box.

To modify a component variable:

  1. In the Navigator window, select the component whose variable modifier you want to edit.

  2. Click the Code button at the top of the Properties window to view the Code properties.

  3. Select Variable Modifiers and click the ellipsis (...) button.

    The Variable Modifiers dialog box opens. You can edit the access modifiers or other modifiers as needed.

10.2.11.3 Modifying Code Generation for a Property

The IDE enables form component properties to be initialized in more ways than simply setting static values.

The IDE enables you to initialize property values from:

  • A static value you define

  • A component written to the JavaBeans architecture

  • A property of another component on the form

  • A call to a method of the form or one of its components. You can choose from a list of methods that return the appropriate data type.

  • Code you define, to be included in the generated code

To modify the initialization code for a component's property:

Follow these steps to modify the initialization code generated for a component's property:

  1. Select the component in the Navigator window.

  2. Click the Properties button at the top of the Properties window.

  3. Select the property for which you would like to modify the initialization code.

  4. Click the ellipsis (...) button to bring up the Property Editor dialog box.

  5. Select Form Connection from the Select Mode combo box.

  6. In the Property Editor, select the type of initialization code you would like to add (Value, Bean, Property, Method Call, or User Code).

    • If you select Value or User Code, you must add a static value or your custom initialization code in the field provided.

    • If you select Bean, Property, or Method Call, you can select from a list of valid options.

    The IDE adds the new code to the selected component's guarded block.

Note:

You can also place custom code before or after a property's initializer. To do this, follow steps 1 through 4 above, and then click the Advanced button to bring up the Advanced Initialization Code dialog box. Type your custom pre-initialization code, post-initialization code, or both in the fields provided.

10.2.11.4 Modifying GUI Form Code Outside of the IDE

In the IDE each form is comprised of two files:

  • A .java file, which contains the form's Java source code.

  • A .form file, which stores the information that is used to generate the .java file when you make changes to the form in the GUI Builder. This file does not need to be distributed with your application. If you delete this file, you can no longer use the GUI Builder to change the form.

You can edit the .java files using external editors (not while the form is being edited in the IDE), with the following exceptions:

  • Do not modify the content of the initComponents() method. The body of this method is always regenerated when the form is opened in the IDE.

  • Do not remove or modify any of the special comments the GUI Builder places in the source (// GEN-...). They are required for the form to open correctly. These comments are not visible inside the IDE's Source Editor.

  • Do not modify the headers or footers of event handlers.

For more information, see Section 10.2.8, "How to Edit Component Properties," and Section 10.7, "Configuring the GUI Builder."

10.2.12 How to Create a Multiple Document Interface (MDI) Application

The multiple document interface (MDI) model is similar to a traditional computer windowing system in that it includes a desktop above which additional windows float. In a JFC/Swing MDI application, the individual internal windows are all contained within a single enclosing window (i.e. desktop) which users can position, resize, minimize, and close.

To create an MDI application:

  1. Choose File > New to display the New wizard.

  2. In the New File wizard's Project combo box, select the project for which you want to create the form. For more information see Section 10.2.1, "How to Create a New Form."

  3. Expand the Java GUI Forms node and select one of the following templates:

    • JFrame Form builds an MDI application from scratch.

      Note:

      You must also add a JDesktopPane component if you choose this template.

    • MDI Application (in Sample Forms) creates a new MDI form with a JDesktopPane and predefined common menu items.

  4. Click Next.

  5. On the wizard's Name and Location page, enter the form's name in the Class Name combo box, then specify the Location and Package. Click Finish. The IDE displays the new file in the Created File field.

  6. (Optional) If you chose the JFrame Form template, select the JDesktopPane node in the window's Swing category and click anywhere in the form.

  7. (Optional) Add JInternalFrame components to the JDesktopPane container by selecting JInternalFrame components from the Swing category in the window and click in the JDesktopPane container. Alternately, you can copy and paste JInternalFrame components to the JDesktopPane container in the Files or Project window. For more information, see Section 10.2.3, "How to Add a Component to a Form."

    The IDE updates the form's layout and displays the new internal frames in the GUI Builder.

Note:

You can add other components directly to the JDesktopPane container, such as a JTable or JSlider component. However, these have standard properties and users can't manipulate them as they might manipulate components in a JInternalFrame container.

Note:

You can create separate JInternalFrame forms and add these to the JDesktopPane container programmatically at runtime.

10.2.13 How to Create Accessible Forms

To ensure that your GUI forms and the components contained within them meet accessibility requirements, adjust their accessibility properties. A GUI is considered accessible when it works with various assistive technologies, such as screen readers.

The following properties can be edited to aid accessibility:

  • Accessible Name.  Sets the name for the component. By default, the name is set to the component's text property value.

  • Accessible Description.  Sets the description for the component.

  • Accessible Parent.  Sets the name of the accessible parent component.

To edit a form or component's accessibility properties:

  1. In the Navigator window, select the form or component whose accessibility properties you want to modify.

  2. In the Properties window, click the Properties tab and scroll down to the Accessibility properties.

  3. Click the ellipsis (...) button to open the Property Editor and then enter the desired value. Alternately, you can click the current property value to select it and enter a new value.

The IDE stores the updated accessibility information in the selected component.

For additional information, see Section 10.2.1, "How to Create a New Form" and Section 10.2.3, "How to Add a Component to a Form."

10.2.14 How to Preview a Form

To quickly test how your form is displayed when it is compiled and run, click the Test Form button in the GUI Builder toolbar. A dialog box is displayed with the components arranged as they would actually appear on your form.

When you click in a Testing Form dialog box, mouse events are delivered to the actual components and you can see the components "in action." For example, you can move sliders, type into text fields, and buttons look "pressed" when you click them, however, cross-component and event handling code is not executed.

To test your form without compiling and running it:

Click the Preview Design button located in the GUI Builder toolbar. The IDE displays the form in the Preview window enabling you to test the behavior of your GUI.

Note:

If you update your form, close any open form Preview windows and click the Preview Design button again to see your changes.

10.3 Working with Layout Managers

Layout managers enable you to control the way in which visual components are arranged in GUI forms by determining the size and position of components within containers. This is accomplished by implementing the LayoutManager interface.

By default, new forms created with the GUI Builder use the GroupLayout layout manager. The IDE has special support for GroupLayout called Free Design. Free Design enables you to lay out your form using visual guidelines that automatically suggest optimal alignment and spacing of components. As you work, the GUI Builder translates your design decisions into a functional UI without requiring you to specify a layout manager. Because Free Design employs a dynamic layout model, whenever you resize the form or switch locales the GUI adjusts to accommodate your changes without changing the relationships between components.

You can combine FreeDesign containers and containers using other layout managers together in the same form.

Note:

GroupLayout was added to version 6 of the Java Platform. If you must deploy your application to version 5 of the Java Platform, you must use the version of GroupLayout that is in the Swing Layout Extensions library. You can set the version of GroupLayout in the property sheet for each form. With the form selected in the Design view, select the form's root node in the Navigator window, and change the Layout Generation Style property.

Note:

New containers added to forms created in earlier versions of the IDE do not assume the FreeDesign layout manager in order to ensure code compatibility. However, it can be set manually in the Set Layout submenu.

Other Layout Managers

You can use other layout managers in the IDE, which might be necessary if you are working with forms created in earlier versions of the IDE, or if you want your form to be compatible with Java Platform version 5 or earlier.

You can choose from the following Layout Managers in the IDE:

For additional information see Section 10.3.1, "How to Set the Layout Manager," Section 10.3.2, "How to Use the GridBag Customizer," and Section 10.3.3, "How to Use a Custom Layout Manager."

10.3.1 How to Set the Layout Manager

When you create a new container, it is generally created using GroupLayout so that you can take advantage of the IDE's Free Design features. If necessary, you can change the layout of most containers using the window, GUI Builder, or Navigator window.

To set the layout manager from the GUI Builder:

  1. Right-click the container whose layout you wish to change.

  2. In the contextual menu, choose the desired layout from the Set Layout submenu.

    The IDE applies the specified layout manager to the selected container.

To set the layout manager from the Navigator window:

  1. Right-click the node for the container whose layout you wish to change.

  2. In the contextual menu, choose the desired layout from the Set Layout submenu.

    The IDE applies the specified layout manager to the selected container.

When you change layouts, the IDE remembers the properties of the discarded layout manager. If you then revert back the to the previous layout manager, the form also returns to its prior state.

For more information see Section 10.3, "Working with Layout Managers," Section 10.3.3, "How to Use a Custom Layout Manager," and Section 10.3.4, "How to Set Layout Properties."

10.3.2 How to Use the GridBag Customizer

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. The GUI Builder more closely reflects how the components look at runtime.

To use the GridBag customizer:

  1. Add the components you require to your form and ensure the GridBagLayout is set for it.

  2. To open the customizer, right-click the GridBagLayout node in the Navigator window and choose Customize from the contextual menu.

  3. Drag the components in the right pane to reposition them as desired. As you drag a component, its Grid X and Grid Y properties change to reflect its new position.

  4. Once the approximate layout of the components has been established, select a component and adjust its constraints as desired in the left pane. You can either enter the values directly or use the provided buttons to adjust the component's constraints.

    Note:

    While editing you might need the Redo, Undo, Pad, and Test Layout buttons in the toolbar above the right pane.

  5. Once you are satisfied with the layout, click Close to exit the customizer.

    The IDE updates the edited components to reflect there new positions.

Adjustable constraints:

  • Grid X and Grid Y.  Fine-tune the component's horizontal and vertical position if necessary by setting its X and Y grid positions.

  • Grid Width and Grid Height.  Set Grid Width and Grid Height to specify how many grid positions are allocated for the component in each direction. Specify one of:

    • An integer value - the number of cells the component uses, (not the number of pixels)

    • Remainder - to make the component the last one in its row or column, using all remaining horizontal or vertical space

    • Relative - to specify that the component be the next to last one in its row or column

  • Fill.  The Fill constraint controls whether the component uses all of the allocated vertical or horizontal space (or both). Use the Grid Size buttons to adjust the Fill constraint. Any filled allocated space is marked with green in the right pane.

  • Internal Padding X and Y.  The internal padding settings enable you to increase the horizontal and vertical dimensions of the component. To adjust these enter numerical values for the properties.

  • Anchor.  The Anchor constraint controls the component placement in one of eleven positions within the allocated space (Center, North, North-West, and so on). This setting has no effect if there is no free space remaining for the component.

    You can also adjust the Anchor constraint using the Grid Size buttons.

  • Weight X and Weight Y.  Adjust the weight settings to determine how much space a component should be given relative to other components in its row or column when the container window is resized. Generally, weight values range from zero to one. Components with larger weight values get more space allocated in their row or column when the window is resized.

    Components with a weight value of zero always retain their preferred size for that dimension. If all the components in a row or column have a weight of zero, any extra space goes to the outer edges of the row or column and the components stay the same size.

  • Insets.  The Insets determine the minimum amount of external space on each of the four sides of the component. Values can be entered manually. As you change the insets, you see the inset area marked by a green background in the right pane.

Note:

It is often helpful to sketch out the way you want your layout to look before you use the GridBag customizer.

For more information see Section 10.3, "Working with Layout Managers," Section 10.3.3, "How to Use a Custom Layout Manager," and Section 10.3.4, "How to Set Layout Properties."

10.3.3 How to Use a Custom Layout Manager

If you are unable to accomplish the result you require with the provided layout managers (Section 10.3.1, "How to Set the Layout Manager."), use a custom layout manager.

To integrate a custom layout manager into the IDE's GUI Builder it must:

  • Implement the java.awt.LayoutManager interface.

  • Be a JavaBeans component.

  • Not use layout parameters (constraints) for individual components.

Note:

If the layout manager does not meet the above requirements, you must create a special support class in order to add it to the GUI Builder.

To install a custom layout manager from the Files window:

  1. Right-click the layout manager's class in the Files window and choose Tools > Add to from the contextual menu.

  2. In the Select Category dialog box, select one of the categories and click OK.

    The IDE adds the custom layout manager to the window.

    For related information see Section 10.3, "Working with Layout Managers."

To install a custom layout manager that is packed in a JAR file:

  1. Choose Tools > Palette > Swing/AWT Components.

  2. In the Palette Manager, click Add From JAR.

  3. In the Install Components to Palette wizard's file chooser, navigate to and select the JAR file for the layout manager.

  4. Complete the Install Components to Palette wizard and click Finish.

    The IDE installs the JavaBean and adds the custom layout manager to the window.

10.3.4 How to Set Layout Properties

To modify the appearance of your forms adjust the general layout manager properties as well as properties specific to any components.

In the IDE you can modify:

  • General layout properties which effect all components in a container, such as alignment of components and gaps between the components.

  • Layout properties specific to a component that is managed by a particular layout manager and which apply to that component alone. These type of properties are also known as constraints.

To set general layout manager properties:

  1. Select the layout manager's node in the Navigator window.

  2. In the Properties window, select the property you want to edit and enter the desired value.

    Note:

    The properties vary depending on the layout manager and that some layout managers do not have any properties.

    The IDE updates all effected components' positions.

    For more information see Section 10.3, "Working with Layout Managers," and Section 10.3.1, "How to Set the Layout Manager."

To set layout properties of components:

  1. Select the component in the Navigator window.

  2. Click the Properties button at the top of the Properties window.

  3. Scroll down to Layout properties, select the property you want to edit and enter the desired value.

    The IDE automatically updates the component's layout behavior.

    For more information see Section 10.2.2, "How to Work with Containers."

Note:

Not all layout managers use constraints. FlowLayout, GridLayout, and BoxLayout) do not have Layout properties so component layout is determined by component order.

10.4 Adding a Bean to the Window

To expand the IDE add your own beans to the window for use in visual design. See Section 10.2.3, "How to Add a Component to a Form." Once the bean is installed, select it in the window, compile it, and add the bean to your forms. You must compile a bean before it can be added to the window.

If the bean you add does not have an icon, the IDE assigns a default icon. To see the name of each installed bean in the window, position the pointer over the bean to view the tool tip.

Note:

If you alter a JavaBeans component that is used in a form, those changes are not automatically reflected in the GUI Builder. To apply any changes you have made to a component and cause them to appear in the form, recompile the component. Then reload the form by pressing Ctrl+Shift+R in the GUI Builder or the Source Editor.

To add a bean to the window:

  1. Choose Tools > Palette > Swing/AWT Components.

  2. If you want to create a new category for the bean, right-click in the Palette window to open the context menu. Choose Create New Category and enter the desired name before you add the bean.

  3. Click Add from JAR, Add from Library, or Add from Project and complete the wizard to add the bean. You must specify either a Jar, a library or a project that contain the corresponding bean's.class file that you want to add to the Window.

Note:

To add a bean to the Palette window, right-click the bean's node in the Projects window and choose Tools > Add To Palette.

10.5 Working with Database Applications and Beans Binding

The following table outlines the basic process of binding properties between JavaBeans components.

Table 10-2 Basic Beans Binding Procedure

Task Description

Create GUI forms

See Section 10.2.1, "How to Create a New Form."

Add components

See Section 10.2.3, "How to Add a Component to a Form."

Add necessary components to the form, including custom beans for which you create bindings.

Bind component properties

  1. Right-click a component in the Source Editor Design view, or in the Navigator window, and choose a target property from the Bind menu. The Bind dialog box opens.

  2. In the Binding tab, specify the source for the binding.

  3. In the Advanced tab, specify any other customizations to the binding, if necessary. For example, some bindings require custom converters, validators, and code for handling unreadable or non-existent values from the source.

For more on binding beans, see Section 10.5.1, "How to Bind Two Bean Properties," Section 10.5.2, "How to Bind Data to a Swing Components," and Section 10.5.3, "How to Use Special Binding Properties (Java Desktop Applications)."


10.5.1 How to Bind Two Bean Properties

Once you have created a new Java form and added components to the form, you can generate code to bind component properties. Binding keeps the values of those properties synchronized.

To prepare components for binding:

Before binding component properties, do the following:

  • Add components to a form in the GUI Builder.

  • Determine which component is the source of the binding and which is the target.

    The binding source is where a value for the property first originates. When binding in the GUI Editor, you initiate a binding on the target and then you declare the source in the Bind dialog box.

Note:

Bindings can be two-way (read/write), so that changes in the target are automatically reflected in the source. However, the direction of the initial binding is always from the source to the target. You can set the update behavior of bindings on the Bind dialog box Advanced tab.

To bind two properties:

  1. In the GUI Builder, right-click the component that is the target of the binding, select Bind, and choose the property that you want to bind from the Bind submenu.

  2. From the Binding Source combo box, select the component that contains the property to which you want to bind.

  3. From the Binding Expression combo box, select the property to which you want to bind.

  4. Optionally, select the Advanced tab to further configure the binding. For example, you can change the update strategy, specify a validator or converter, and specify whether the binding source is null or unreadable.

  5. Click OK.

10.5.2 How to Bind Data to a Swing Components

Once you have created a new Java form and added components to the form, you can generate code to bind those components to data. The IDE makes it easy to bind data to Swing JTable and JList components.

Before binding a component to a database, must have completed the following tasks:

  • Connect to a database in the IDE.

  • Add the component to a form in the GUI Builder.

  • Create entity classes that represent the database tables to which you want to bind. Entity classes are special classes that use the Java Persistence API (JPA). Steps on creating the entity classes for binding data to a component are given below.

To create entity classes to represent the database to be bound to the JTable:

  1. In the Projects window, right-click your project and choose New > Other, select the Persistence category, and select the Entity Classes from Database template.

  2. In the Database Tables page of the wizard, select the database connection.

  3. Once the Available Tables column is populated, select the tables that you want to use in your application and click Add to move them to the Selected Tables column. Click Next.

  4. In the Entity Classes page of the wizard, make sure the Generate Named Query Annotations for Persistent Fields dialog box is selected.

  5. Make any customizations that you want to make to the names of the generated classes and their location.

  6. Click Create Persistence Unit.

  7. In the Create Persistence Unit dialog box, make sure of the following things:

    • The selected Persistence Library is TopLink.

    • The selected Table Generation Strategy is "None."

  8. Click Finish.

    You should see nodes for the entity classes in the Projects window.

To bind the data to a JTable component:

  1. Right-click the component in the GUI Builder and choose Bind > elements.

  2. Click Import Data to Form. From the Import Data to Form dialog box, select the database table to which you want to bind your components. Click OK.

  3. From the Binding Source combo box, select an item that represents the result list of the entity class. For example, if the entity class is called, Customer.java, the list object would be generated as customerList.

  4. Leave the Binding Expression value as null.

  5. In the Display Expression drop-down list, select the property that represents the database column that contains the values that you want to display in the list.

  6. Select the Advanced tab to further configure the binding.

  7. Click OK.

10.5.3 How to Use Special Binding Properties (Java Desktop Applications)

Where necessary, the beans binding library provides special synthetic properties for some Swing components that are missing from the components themselves. These properties represent data selections, such as a table's selected row, that are useful to bind to other properties.

Table 10-3 Beans Binding Library Synthetic Properties

Component Property Description

AbstractButton

selected

The selected state of a button.

JComboBox

selectedItem

The selected item of a JComboBox.

JSlider

value

The value of a JSlider; notifies of all changes.

 

value_IGNORE_ADJUSTING

Same as "value" but does not notify of change while the slider is adjusting its value.

JList

selectedElement

The selected element of a JList; notifies of all changes. If there is a JListBinding with the JList as the target, the selected element is reported as an element from the binding's source list. Otherwise, the selected element is reported as an object from the list's model. If nothing is selected, the property evaluates to null.

 

selectedElements

A list containing the selected elements of a JList; notifies of all changes. If there is a JListBinding with the JList as the target, the selected elements are reported as elements from the binding's source list. Otherwise, the selected elements are reported as objects from the list's model. If nothing is selected, the property evaluates to an empty list.

 

selectedElement_IGNORE_ADJUSTING

Same as "selectedElement" but does not notify of change while the list selection is being updated.

 

selectedElements_IGNORE_ADJUSTING

Same as "selectedElements" but does not notify of change while the list selection is being updated.

JTable

selectedElement

The selected element of a JTable; notifies of all changes. If there is a JTableBinding with the JTable as the target, the selected element is reported as an element from the binding's source list. Otherwise, the selected element is reported as a map where the keys are composed of the string "column" plus the column index and the values are the model values for that column. Example: {column0=column0value, column1=column1value, ...} If nothing is selected, the property evaluates to null.

 

selectedElements

A list containing the selected elements of a JTable; notifies of all changes. If there is a JTableBinding with the JTable as the target, the selected elements are reported as elements from the binding's source list. Otherwise, each selected element is reported as a map where the keys are composed of the string "column" plus the column index and the values are the model values for that column. Example: {column0=column0value, column1=column1value, ...} If nothing is selected, the property evaluates to an empty list.

 

selectedElement_IGNORE_ADJUSTING

Same as "selectedElement" but does not notify of change while the table selection is being updated.

 

selectedElements_IGNORE_ADJUSTING

Same as "selectedElements" but does not notify of change while the table selection is being updated.

JTextComponent (including its sub-classes JTextField, JTextArea, and JEditorPane)

text

The text property of a JTextComponent; notifies of all changes (including typing).

 

text_ON_FOCUS_LOST

The text property of a JTextComponent; notifies of change only when focus is lost on the component.

 

text_ON_ACTION_OR_FOCUS_LOST

The text property of a JTextComponent; notifies of change only when the component notifies of actionPerformed or when focus is lost on the component.


For related information, see Section 10.2.3, "How to Add a Component to a Form," Section 10.5.2, "How to Bind Data to a Swing Components," and Section 10.5.1, "How to Bind Two Bean Properties."

10.5.4 How to Convert Values Between Source and Target Properties (Java Desktop Applications)

When you bind the values of two properties of two objects, you must sometimes convert the values between different types.

The beans binding library contains converters for some common conversions. For other conversions, you must provide a custom converter.

Below is a list of conversions which do not need converter:

  • BigDecimal to String, String to BigDecimal

  • BigInteger to String, String to BigInteger

  • Boolean to String, String to Boolean

  • Byte to String, String to Byte

  • Char to String, String to Char

  • Double to String, String to Double

  • Float to String, String to Float

  • Int to String, String to Int

  • Long to String, String to BigDecimal

  • Short to String, String to Short

  • Int to Boolean, Boolean to Int

To write a custom converter, create a class that extends org.jdesktop.beansbinding.Converter. Your class needs to override the convertForward(S value) and convertReverse(T value) methods. convertForward(S value) converts a value from the source type to the target type. convertReverse(T value) converts a value from the target type to the source type.

To use a custom converter in a binding:

  1. Right-click the converter class in the Projects window and choose Compile File.

  2. Drag the converter from the Projects window to the Design view of your form. The converter is added to your form as a bean.

  3. Right-click the target of your binding and choose Bind > TargetProperty.

  4. In the Bind Dialog box, select the Advanced tab.

  5. From the Converter drop-down list, choose the converter you have added to the form.

  6. Click OK.

Note:

You can also add the conversion code directly. Click the ellipsis (...) button, and select Custom Code from the Select Converter Property Using drop-down list.

For related information, see Section 10.5.5, "How to Validate Target Value Changes in Bindings (Java Desktop Applications)," Section 10.5.2, "How to Bind Data to a Swing Components," and Section 10.5.1, "How to Bind Two Bean Properties."

10.5.5 How to Validate Target Value Changes in Bindings (Java Desktop Applications)

When you bind the values of two properties of two objects, you sometimes must validate any changes to the target property before they are written back to the source (such as a database). To validate a target, specify a validator that extends org.jdesktop.beansbinding.Validator.

To write a custom validator, create a class that extends org.jdesktop.beansbinding.Validator. Your class needs to implement the validate(T value) method. For a valid value, validate(T value) returns null. For an invalid value, it returns a Result object describing the problem for the invalid value.

To use a custom validator in a binding:

  1. Right-click the validator class in the Projects window and choose Compile File.

  2. Drag the validator from the Projects window to the Design view of your form.

    The validator is added to your form as a bean.

  3. Right-click the target of your binding and choose Bind > TargetProperty.

  4. In the Bind Dialog box, select the Advanced tab.

  5. From the Validator drop-down list, choose the validator you have added to the form.

  6. Click OK.

Note:

To add the validation code directly, click the ellipsis (...) button. From the Select Validator Property Using drop-down list, select Custom Code.

For additional information see Section 10.5.1, "How to Bind Two Bean Properties," Section 10.5.2, "How to Bind Data to a Swing Components," and Section 10.5.4, "How to Convert Values Between Source and Target Properties (Java Desktop Applications)."

10.6 Deploying GUI Applications

In order for the applications that you create to work outside of the IDE, you might have to include some extra JAR files when you deploy the application.

The swing-layout-1.0.3.jar file might be needed by your deployed applications. This library contains the various layout-related extensions, such as the GroupLayout layout manager. This library is included in version 6 of the Java Platform, so you do not need to package it with your application if you are deploying it to environments that have version 6 of the JRE.

Note:

As of JDK 6, the Beans Binding library is not part of the Java Platform.

You can find these JAR files in the following folders on your system:

10.6.1 Preparing a GUI Application for Distribution

To ensure that your GUI application can reference these libraries at runtime, the IDE automatically copies the library JAR files (and any other JAR files on the project's classpath) to the dist/lib folder whenever you build the project. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf file.

Note:

If your application does not make use of the support of one of these libraries, that library is not included in the dist/lib folder.

To prepare your GUI application for distribution outside of the IDE:

Zip the project's dist folder (including the lib folder) into a ZIP archive.

10.6.2 Running a Standalone GUI Application

Once you have distributed an archive of your GUI application, your application can be run outside of the IDE from the command line.

To run a standalone GUI application from the command line:

  • Navigate to the project's dist folder.

  • Type the following:

    java -jar jar_name.jar

For a discussion of GUI Builder capabilities, see Section 10.2, "Working with the GUI Builder."

10.7 Configuring the GUI Builder

You can adjust how the IDE's GUI Builder generates code and how the GUI Builder design looks.

Note:

If you want to edit settings for a particular form, select the form's root node in the Navigator window and click the Code button in the Properties window. For additional information see Section 10.2.11, "How to Modify GUI Source Code."

To configure GUI Builder settings for all projects:

  1. Choose Tools > Options from the main window.

  2. Click the Java category.

  3. Click the GUI Builder tab to display the editable GUI Builder Settings.

  4. Select and edit the property you wish to change.

The IDE applies the new settings to the GUI Builder.

For more on how to adjust a component's appearance and behavior, see Section 10.2.8, "How to Edit Component Properties," and Section 10.3.4, "How to Set Layout Properties."