20 Implementing Java Swing User Interfaces

This chapter describes how to use the tools and features that JDeveloper provides to help you develop Java Swing interfaces. It explains the fundamental tasks you perform as you work with components and JDeveloper's UI design tools. Included is a description of the UI debugger, which is used to debug user interfaces specifically for AWT and Swing-based client applications and applets.

This chapter includes the following sections:

20.1 About Implementing Java Swing User Interfaces

Using the Java Visual Editor in JDeveloper, you can quickly and easily assemble the elements of a user interface (UI) for a Java application or applet using Swing components. You construct the UI with JavaBeans selected from the component palette, such as buttons, text areas, lists, dialogs, and menus. Then, you set the values of the component properties and attach event-handler code to the component events.

20.2 Understanding the JDeveloper User Interface Design Tools

With JDeveloper tools, you can visually design and program Java classes to produce new compound or complex components.

JDeveloper UI design tools include the following:

  • A Java Visual Editor in which you create and arrange panels and other UI components inside a frame or other UI container. You access the Java Visual Editor by right clicking the file in the Navigator and choosing Open. Click the Design tab to work the visual editor. For more information, see Section 18.3.1, "Editing Code with the Java Visual Editor."

  • A Menu Editor in which you create and edit a menu bar, menus, menu items, and popup menu components. You access the Menu Editor when you have the Java Visual Editor open by dropping a menu component into your UI container from the Component Palette. You can also edit an existing menu component by clicking the menu component in the Structure window. For more information, see Section 20.9.2, "Using the Menu Editor."

  • A Component Palette containing visual and nonvisual components. You display the Component Palette for components that you select in the Java Visual Editor. To display the Component Palette for an open file, choose View > Component Palette. For more information, see Section 11.1.4, "How to Use the Component Palette."

  • A Structure window that displays a hierarchical view of all the components in your source file, and their relationships. You access the Structure window below the Navigator window or, if docked, by choosing View > Structure. For more information, see Section 3.11.6, "Structure Window."

  • The Property Inspector, used to inspect and set component properties and to attach methods to component events. Changes made in the Inspector are reflected visually in the Java Visual Editor and source code. You display the Property Inspector for a particular file that you open in the Java Visual Editor. To display the Property Inspector for an open file, choose View > Property Inspector. For more information, see Section 11.1.3, "How to Use the Property Inspector."

If you want to use the UI design tools on a file, it must meet the following requirements:

  • It must be a Java file.

  • It must be free from syntax errors.

  • It must contain a public class (the file name must be the same as the name of the public class).

  • It must follow JDeveloper coding conventions:

    • All UI controls are declared as class members or as local variables within jbInit().

    • All UI property settings done in jbInit(). This is necessary in order for the JDeveloper Java Visual Editor and Property Inspector to reflect the settings.

    • All property settings set as expressions involve only member UI controls or static values.

  • It must have a default constructor.

Any file that meets the above requirements can be visually designed using the Java Visual Editor and the Property Inspector. You can also visually design a non-UI class.

Note:

These requirements are satisfied when you create your files with any of the JDeveloper dialogs.

When you first add a component to your design, the JDeveloper Java Visual Editor ensures that your class has a default constructor, a private jbInit() method, and that this jbInit() method is called correctly from the default constructor. If JDeveloper does not find this code, it will add it. It will also add any imports needed by the component.

When you open the file in the Java Visual Editor, JDeveloper updates the Structure window tree. For example, if your class has a frame and a menu, there will be subtrees for UI and Menu. If you drop any other JavaBeans components into the Structure window, an 'Others' folder appears so you can select and edit these components in the Property Inspector.

20.3 Controlling the Look and Feel of a Swing Application

JDeveloper includes the Swing GUI components. The Swing classes allow you to specify a look and feel for a user interface. You can take advantage of this new Java pluggable look-and-feel to create applications that have the look and feel of a user's native desktop for Windows or Solaris machines. You can also ensure a uniform look and feel in your applications across platforms with the Java Metal look and feel.

There are four look and feel choices in JDeveloper:

  • Oracle

  • Metal

  • CDE/Motif

  • Windows

There are also several considerations when setting the look and feel using the UI Manager:

  • The line of code for the look and feel statement is inside a try/catch block. This placement is necessary for it to compile.

  • This code needs to be run before any components are instantiated. That is why it is placed in the <Application>.java static main() method.

  • The class UIManager lives in the com.sun.java.swing package.

20.3.1 How to Change the Oracle Look and Feel

To change to the Oracle look and feel:

  1. Open the Application file in the Code Editor.

  2. In the Main method, add the following code:

    try {
         UIManager.setLookAndFeel(new oracle.bali.ewt.olaf.OracleLookAndFeel());
    }
    catch (Exception e) {
    }
    

    It is necessary to have the Oracle look and feel (OLAF) share.jar and jewt4.jar files from the jlib directory in the classpath.

20.3.2 How to Change the Windows Look and Feel

To change to the Windows look and feel:

  1. Open the Application file in the Code Editor.

  2. In the Main method, add the following code:

    try {
         UIManager.setLookAndFeel(new 
          com.sun.java.swing.plaf.windows.WindowsLookAndFeel());
    }
    catch (Exception e) {
    }
    

    It is necessary to have the Oracle look and feel (OLAF) share.jar and jewt4.jar files from the jlib directory in the classpath.

20.3.3 How to Change the Metal Look and Feel

The Metal look and feel is default for Swing components. If you want to use the Metal look and feel, you do not have to change your code.

To change to the Metal look and feel:

  1. Open the Application file in the Code Editor.

  2. In the Main method, add the following code:

    try {
         UIManager.setLookAndFeel(new 
          javax.swing.plaf.metal.MetalLookAndFeel());
    }
    catch (Exception e) {
    }
    

Note:

It is necessary to have the Oracle look and feel (OLAF) share.jar and jewt4.jar files from the jlib directory in the classpath.

20.4 Working with Java Swing and AWT Components

Use Swing and AWT JavaBeans components to assemble the user interface (UI) for a Java application or applet. You construct the UI in the Java Visual Editor by selecting JavaBeans from the Component Palette, such as buttons, text areas, lists, dialogs, and menus. Then, you set the values of the component properties and attach event-handler code to the component events. Tools to visually design and program Java classes to produce new compound or complex component.

20.4.1 Using Swing JavaBeans Components

Swing components are lightweight components that are self-rendering and do not use Windowing resources as do AWT components. In many cases, these components have corresponding AWT components, but the Swing version is enhanced to allow greater flexibility and consistency between platforms.

Note:

Swing components rely on underlying functionality in Swing containers. If you intend to use Swing JavaBeans, you must create your program using a JFrame, JPanel or other container that implements the basic Swing functionality.

Table 20-1 contains the Swing JavaBeans components.

Table 20-1 Swing JavaBeans Components

Component Description

JButton

A simple push button. A JButton can have an embedded icon.

JCheckBox

A square box used to display boolean (true/false) values. When its value is set to true, the box displays a checkmark by default. You have the option of setting your own checkmark graphic.

JComboBox

Similar to the Choice control in AWT, displays a list of values that the user can select at runtime. JComboBox has the property editable which enables the user to type a new value at runtime.

JEditorPane

A specialized JTextComponent that displays text formatted with HTML 3.2 or RTF. It is intended to allow you to create help pages for your application or applet.

JLabel

A text component that enables you to display a text string and optional icon. Additional properties enable you to set the position of the text relative to the icon.

JList

Displays a list of objects.

Tip: The JList, unlike the AWT List component, doesn't have a scrolling facility built into the component. To make a scrollable list, you need to drop the list component into a JScrollPane container.

JPasswordField

A JTextField that by default displays asterisks (*) in place of the characters entered by the user.

JProgressBar

Displays a progress bar that graphically depicts the percentage of completion for a process.

JRadioButton

This component is specifically designed to behave as a Radio Button. When grouped with other JRadioButtons in a ButtonGroup, only one of the buttons in the group can be selected at one time. The ButtonGroup is a non-visual component.

JScrollBar

A graphic control the user can use to set an integer value. This component can be displayed with either a horizontal or a vertical orientation.

JSeparator

A component that draws a straight line. It is intended to be used as a component in a JMenu, but since it is an actual component, you can use it to draw a line in your UI that separates one set of controls from another. The JSeparator can be displayed in vertical or horizontal orientation.

JSlider

Similar to a JScrollBar, this control allows the user to set an integer value using a graphic control. JSlider allows you to set major and minor tick marks, and to display a border around the control.

JTable

Displays information in a two-dimensional grid, similar to a spreadsheet application.

Tip
: The JTable, unlike the AWT List component, doesn't have a scrolling facility built into it. To make a scrollable table, you need to drop the list component into a JScrollPane container.

JTextArea

An editable text area that displays a single string in multiple rows, each of which ends in a newline character.

Tip: In order to make a JTextArea scrollable, it needs to be displayed in a JScrollPane container.

JTextField

An editable text area that displays a single string in a single row.

JTextPane

A full-featured text editor control that enables word wrap, image display, and style definition.

Tip
: In order to make a JTextPane scrollable, it needs to be dropped in a JScrollPane container.

JTree

Displays hierarchical information, such as file directories, in a tree format.

Tip: The JTree, unlike the AWT List component, doesn't have a scrolling facility built into it. To make a scrollable tree, you need to drop the list component into a JScrollPane container.

JToggleButton

Toggle buttons are similar to JCheckBox controls. When they are pushed (set to true) they remain true until they are set to false by pressing them again. JToggleButtons can be placed in a ButtonGroup so that only one in the group can be true at one time. Toggle buttons are useful in toolbars to display a tool in an active state. The buttons in the Component Palette are examples of toggle buttons.


20.4.2 Using AWT JavaBeans

AWT JavaBeans components use the standard controls of the underlying platform to display the user interface. This architecture makes AWT components simple and straightforward to implement, but limits control over the final display of the UI and reduces flexibility. They also require more system resources to run, which is why they are sometimes referred to as heavyweight components. Swing components are implemented in Java to be self-rendering and therefore make less use of system resources, which is why they are referred to as lightweight components. Swing components can be more complex to implement, but offer greater flexibility and consistency between host platforms.

Table 20-2 contains the AWT JavaBeans Components.

Table 20-2 AWT JavaBeans Components

Component Description

Button

Displays a simple push button

Checkbox

True/false, on/off boolean control. As a standalone component, the checkbox appears as a square with an X to indicate when its value is set to true. When set as a member of a checkbox group, the checkbox becomes a circle (Radio Button): a dot in the circle indicates that its value is set to true. Add a checkbox component to a CheckboxGroup by setting its CheckboxGroup property to the name of the CheckboxGroup to which it belongs.

CheckboxGroup

Non-visual component used to integrate the behavior of a set of check box components. Only one item in a checkbox group can be set to true at one time. Checkbox components are added to the CheckboxGroup by setting the CheckboxGroup property to the name of the corresponding CheckboxGroup. The default value for a CheckboxGroup can be set by setting its SelectedCheckbox property to the name of the checkbox component.

Tip: Depending on the order in which you add the Checkbox components and CheckboxGroup, the CheckboxGroup may be instantiated before the Checkboxes. To ensure that the correct default is set, you can move the SelectedCheckbox and current initialization statements to the bottom of the JbInit method so that all of its constituents are instantiated before the default is set.

Choice

Displays a popup menu. The label of the Choice control is the currently selected item. This is similar to a combobox.

Label

Displays a non-editable text label in the application, though its value may change programmatically.

List

Displays a scrolling list of data items. The user may be able to select one or more items depending on the property settings of the List.

MenuBar

Displays a menubar. Any container can add a MenuBar control as a child, however only Frame has the setMenubar() method which will parent the MenuBar at a specific location and will not interfere with the locations of any other children. Menubars are not available in Applets.

PopupMenu

Displays a popup menu with a list of commands. Popup menus can be attached to panels, and are available for use in Applets. For more information about creating menus, see Section 20.9, "Working with Menus".

Panel

A container which is used to display a group of controls. Each panel can have its own layout to give you control over the positioning of components in relation to one another.

Scrollbar

A slider control that allows the user to set an integer value. The scrollbar can be set to display horizontally or vertically.

ScrollPane

A type of panel that has horizontal and vertical scrollbars available to enable you to display a child component that is larger than the ScrollPane itself.

TextArea

A text component that displays a single string of text in multiple rows, each ending with a newline character. Text can be scrolled up and down, left and right.

TextField

An editable text component that displays a single string of text in a single row.


20.5 Working with Layout Managers

Use JDeveloper's layout managers to control how components are located and sized in the container each time it is displayed. A layout manager automatically arranges the components in a container according to a particular set of rules specific to that layout manager.

A Java program can be deployed on more than one platform. If you use standard UI design techniques of specifying absolute positions and sizes for your UI components, your UI might not look good on all platforms. What looks fine on your development system might be unusable on another platform. To solve this problem, Java provides a system of portable layout managers. Layout managers allow you to specify rules and constraints for the layout of your UI in a way that will be portable.

Layout managers give you the following advantages:

  • Correctly positioned components that are independent of fonts, screen resolutions, and platform differences.

  • Intelligent component placement for containers that are dynamically resized at runtime.

  • Ease of translation with different sized strings. If a string increases in size, the components stay properly aligned.

A Java UI container uses a special object called a layout manager to control how components are located and sized in the container each time it is displayed. A layout manager automatically arranges the components in a container according to a particular set of rules specific to that layout manager.

The layout manager sets the sizes and locations of the components based on various factors such as:

  • the layout manager's layout rules

  • the layout manager's property settings, if any

  • the layout constraints associated with each component (for more information, see Section 20.5.24, "Understanding Layout Constraints").

  • certain properties common to all components, such as preferredSize, minimumSize, maximumSize, alignmentX, and alignmentY

  • the size of the container

In Java, certain types of containers use specific layout managers by default.

  • All panels (including applets) use FlowLayout.

  • All windows (including frames and dialog boxes) use BorderLayout.

When you create a container in a Java program, you can accept the default layout manager for that container type, or you can override the default by specifying a different type of layout manager.

Normally, when coding your UI manually, you override the default layout manager before adding components to the container. When using the Java Visual Editor, you can change the layout whenever you like. JDeveloper will adjust the code as needed.

The Java Visual Editor in JDeveloper uses a default layout manager for each container, usually null layout. If you want to use a different layout manager than the default, you can do so by explicitly adding a layout manager to the source code for the container, or by selecting a layout from the container's layout property list in the Inspector.

Note:

If you want to change the properties for a layout manager using the Java Visual Editor, you must explicitly specify a layout for a container so its properties will be accessible in the Property Inspector.

Choose a layout manager based on the overall design you want for the container. Some layouts can be difficult to work with in the Java Visual Editor because they immediately take over placement and resizing of a component as soon as you add it to the container. To alleviate this problem during initial layout prototyping, JDeveloper provides a default layout called null, which leaves the components exactly where you place them and at the size you specify. Starting with an null makes prototyping easier in your container. Later, after adding components to the container, you can switch to an appropriate portable layout for your design.

In some designs, you might use nested panels to group components in the main Frame, using various different layouts for the Frame and each of its panels.

Note:

If you really want to design a panel without a layout manager, you can set the layout manager in the source code to null. However, you should not leave it this way for deployment.

Experiment with different layouts to see their effect on the container's components. If you find the layout manager you've chosen doesn't give you the results you want, try a different one, or try nesting multiple panels with different layouts to get the desired effect.

20.5.1 Understanding Sizing Properties

Layout managers use various pieces of information to determine how to position and size components in their container. Components provide a set of methods that allow layout managers to intelligently lay out components. All of these methods allow a component to communicate its desired sizing to the layout manager.

The methods in Table 20-3 are property getters and represent the following:

Table 20-3 Sizing Properties

Method Description

getPreferredSize()

The size a component would choose to be, that is, the ideal size for the component to look best. Depending on the rules of the particular layout manager, the preferredSize may or may not be considered in laying out the container.

getMinimumSize()

How small the component can be and still be usable. The minimumSize of a component may be limited, for example, by the size of a label. For most controls, minimumSize is the same as preferredSize. Layout managers generally respect minimumSize more than they do preferredSize.

getMaximumSize()

The largest, useful size for this component. This is used so that the layout manager won't waste space on a component that can't use it effectively. For example, BorderLayout could limit the center component's size to its maximum size, and then either give the space to the edge components, or limit the size of the outer window when resized.

getAlignmentX()

How the component would like to be aligned along the x axis, relative to other components.

getAlignmentY()

How the component would like to be aligned along the y axis, relative to other components.


To understand how each layout manager uses these pieces of information, see the individual layouts listed in Section 20.5.2, "Understanding Layouts Provided with JDeveloper".

20.5.2 Understanding Layouts Provided with JDeveloper

JDeveloper provides the following standard layout managers from the Java AWT BorderLayout, FlowLayout, GridLayout, CardLayout, and GridBagLayout. For Swing, BoxLayout2 and OverLayout2 have been included.

JDeveloper also provides FormLayout, a grid-based container that places components in a grid of columns and rows, allowing specified components to span multiple columns or rows. FormLayout is provided by JGoodies Forms, an open source framework included with JDeveloper.

Additionally, JDeveloper provides these custom layouts:

  • XYLayout that keeps components you put in a container at their original size and location (x,y coordinates).

  • PaneLayout, used by the SplitPanel control.

  • VerticalFlowLayout, which is very similar to FlowLayout except that it arranges the components vertically instead of horizontally.

You can create custom layouts of your own, or experiment with other layouts like the ones in the sun.awt classes, or third-party layout managers, many of which are public domain on the Web. If you want to use a custom layout in the Java Visual Editor, you may have to provide a Java helper class file to help the Java Visual Editor use the layout.

20.5.3 Using BorderLayout

BorderLayout arranges a container's components in areas named North, South, East, West, and Center.

  • The components in North and South are given their preferred height and are stretched across the full width of the container.

  • The components in East and West are given their preferred width and are stretched vertically to fill the space between the north and south areas.

  • A component in the Center expands to fill all remaining space.

Figure 20-1 BorderLayout

Border Layout

The BorderLayout that appears in Figure 20-1 is good for forcing components to one or more edges of a container, and for filling up the center of the container with a component. It is also the layout you want to use to cause a single component to completely fill its container.

You will probably find BorderLayout to be the most useful layout manager for the larger containers in your UI. By nesting a panel inside each area of the BorderLayout, then populating each of those panels with other panels of various layouts, you can achieve quite complicated UI designs.

Components are positioned in one of five areas within a BorderLayout, based on the constraints property. You can set the constraints property for the component in the Inspector to one of the following values: North, South, East, West, or Center.

For example, to put a toolbar across the top of a BorderLayout container, you could create a FlowLayout panel of buttons and place it in the North area of the container. You do this by selecting the panel and choosing North for its constraints property in the Inspector.

To set the constraints property:

  1. Select the component you want to position, either in the Java Visual Editor or the Structure window.

  2. Select the constraints property in the Inspector, and click its value field.

  3. Click the down arrow on the constraints property dropdown list and select the area you want the component to occupy.

  4. Press Enter or click anywhere else in the Property Inspector to commit the change to code.

If you use the Java Visual Editor to change the layout of an existing container to BorderLayout, the components near the edges automatically move to fill the closest edge. A component near the center may be set to Center. If a component moves to an unintended location, you can correct the constraints property in the Inspector, or drag the component to a new position in the Java Visual Editor.

Each of the five areas can contain any number of components (or panel of components), however, unless the topmost component is not opaque, any lower components in the same area will be covered by the topmost one.

The following are some general guidelines for working with multiple components and BorderLayout:

  • Make sure the container has no more than five components.

  • Use XYLayout first to move the components to their approximate intended positions, with only one component near each edge.

  • Group multiple components in an area into a panel before converting.

Note:

BorderLayout ignores the order in which you add components to the container.

By default, a BorderLayout puts no gap between the components it manages. However, you can use the Inspector to specify the horizontal or vertical gap in pixels for a BorderLayout associated with a container.

To modify the gap surrounding BorderLayout components, select the BorderLayout object in the Structure window (displayed immediately below the container it controls), then modify the pixel value in the Property Inspector for the hgap and vgap properties.

20.5.4 Using BoxLayout2

BoxLayout2 allows you to arrange a container's components either vertically or horizontally. By nesting components in containers, you can achieve complex layouts. Figure 20-2 shows three panels (P1, P2, P3) arranged vertically. Each panel contains two buttons arranged vertically.

Figure 20-2 BoxLayout2

BoxLayout2

When you use BoxLayout2 for a component, you specify whether its major axis is the Y axis (top placement) or X axis (left to right placement). Components are arranged from left to right (or top to bottom), in the same order as they were added to the container.

BoxLayout2 attempts to arrange components at their preferred widths (for left to right layout) or heights (for top to bottom layout). The components will not wrap if the container is resized.

If all the components are not the same height in a horizontal layout, BoxLayout2 attempts to make all the components as high as the highest component. If that's not possible for a particular component, then BoxLayout2 aligns that component vertically, according to the component's Y alignment.

If the components are not all the same width in a vertical alignment, BoxLayout2 attempts to make all components in the column as wide as the widest component; if that fails, it aligns them horizontally according to their X alignments.

20.5.5 Using CardLayout

CardLayout places components (usually panels) on top of each other in a stack like a deck of cards. You see only one at a time, and you can flip through the panels by using another control to select which panel comes to the top.

CardLayout is a good layout to use when you have an area that can contain different components at different times. This gives you a way to manage two or more panels that need to share the same display space.

20.5.5.1 How to Create a CardLayout Container

You can see an example of using CardLayout by looking at the wizards in JDeveloper. The Cancel, Next, and Back buttons control which panel is displayed next.

To create a CardLayout container:

  1. Create a new Application.

  2. Right-click the frame file in the Navigator and choose Open.

  3. Add a panel to your UI in the Java Visual Editor and set its layout property to CardLayout. For more information, see Section 20.7.9, "How to Create a Panel".

  4. Drop a new panel into the CardLayout panel. This new panel will completely fill up the CardLayout panel.

    Note:

    The first component you add to a CardLayout panel will always fill the panel.
  5. Set the layout property for this new panel to XYLayout and add the desired components.

  6. Click a panel on the Component Palette, then click on the CardLayout panel in the component tree in the Structure window to add it to the stack in CardLayout panel.

  7. Set this second panel to XYlayout and add components to it.

  8. Repeat steps 6 and 7 for each new panel you want to add to the stack.

20.5.5.2 How to Specify the Gap Surrounding a CardLayout Container

Using the Structure window, you can specify the amount of horizontal and vertical gap surrounding a stack of components in a CardLayout.

To specify the gap surrounding a cardLayout container:

  1. Select the cardLayout object in the Structure window, displayed immediately below the container it controls.

    Figure 20-3 cardLayout

    cardLayout
  2. Click the hgap (horizontal gap) or vgap (vertical gap) property in the Inspector.

  3. Enter the number of pixels you want for the gap.

  4. Press Enter or click anywhere else in the Inspector to register the changes.

20.5.6 Using FlowLayout

FlowLayout arranges components in rows from left to right, and then top to bottom using each component's preferredSize. FlowLayout lines up as many components as it can in a row, then moves to a new row. Typically, FlowLayout is used to arrange buttons on a panel.

Figure 20-4 FlowLayout

FlowLayout

Note:

Note: If you want a panel that arranges the components vertically, rather than horizontally, see Section 20.5.21, "Using VerticalFlowLayout".

You can choose how to arrange the components in the rows of a FlowLayout container by specifying an alignment justification of left, right, or center. You can also specify the amount of gap (horizontal and vertical spacing) between components and rows. Use the Inspector to change both the alignment and gap properties when you're in the Java Visual Editor.

Alignment

  • LEFT- groups the components at the left edge of the container.

  • CENTER - centers the components in the container.

  • RIGHT groups the components at the right edge of the container. The default alignment in a FlowLayout is CENTER.

    To change the alignment, select the FlowLayout object in the Structure window, then specify a value in the Property Inspector for the alignment property as follows:

    • 0=LEFT

    • 1=CENTER

    • 2=RIGHT

Gap

The default gap between components in a FlowLayout is 5 pixels.

To change the horizontal or vertical gap, select the FlowLayout object in the Structure window, then modify the pixel value of the hgap (horizontal gap) or vgap (vertical gap) property in the Inspector.

Order of Components

To change the order of the components in a FlowLayout container, drag the component to the new location, or right-click a component and choose Move to First or Move to Last.

20.5.7 Using FormLayout

FormLayout places components in a grid of columns and rows, allowing specified components to span multiple columns or rows. Columns and rows need not have the same width or height.

Note:

FormLayout is provided by JGoodies Forms, an open source framework included with JDeveloper. To add FormLayout layout manager, add JGoodies Forms library in the current project's library.

You can change the following column and row properties. Columns and rows are specified by three parts: a mandatory size, an optional default alignment, and an optional resize behavior. To edit these properties, when you're in the Java Visual Editor, drag the mouse and select the entire FormLayout grid, then right-click inside the selected grid and choose Column Properties or Row Properties.

Alignment

The default alignment of components in a column or row. The default alignment in a FormLayout is Fill.

Size

The width of a column or height of a row. You can specify a constant size, a component size (minimum or preferred), or a bounded size (minimum and maximum). Constant size is specified by a value plus a unit. Component sizes give a column or row the maximum size of its contained components and are measured by the component's minimum or preferred size. Bounded size lets you specify lower and upper bounds for the column and row start size (before resizing). This ensures a minimum or maximum column or row size. Note that the maximum size does not limit the column/row size if the column/row can grow (see resize behavior).

Resize

Controls whether or not resizing is allowed. Columns and rows can grow if the layout container becomes larger than the preferred size. The default is not to allow resizing.

Gap

The default places gaps between components.

Note:

Gap size is currently fixed and can not be edited in the Property Inspector.

Order of Components

To change the order of the components in a FormLayout container, drag the component to the new location.

20.5.8 Using GridLayout

GridLayout places components in a grid of cells that are in rows and columns. GridLayout expands each component to fill the available space within its cell. Each cell is exactly the same size and the grid is uniform. When you resize a GridLayout container, GridLayout changes the cell size so the cells are as large as possible, given the space available to the container.

Figure 20-5 GridLayout

GridLayout

Use GridLayout if you are designing a container where you want the components to be of equal size, for example, a number pad or a toolbar.

You can specify the number of columns and rows in the grid, but only one of the rows or columns can be zero. You must have a value in at least one so the GridLayout manager can calculate the other.

For example, if you specify four columns and zero rows for a grid that has 15 components, GridLayout creates four columns of four rows, with the last row containing three components. Or, if you specify three rows and zero columns, GridLayout creates three rows with five full columns.

In addition to number of rows and columns, you can specify the number of pixels between the cells by modifying the horizontal gap (hgap) and vertical gap (vgap) properties. The default horizontal and vertical gap is zero.

To change the property values for a GridLayout container, select the GridLayout object in the Structure window, then edit the values for the rows, cols, hgap, or vgap properties in the Property Inspector.

20.5.9 Using GridBagLayout

GridBagLayout is an extremely flexible and powerful layout that provides more control than GridLayout in laying out components in a grid. GridBagLayout positions components horizontally and vertically on a dynamic rectangular grid. The components do not have to be the same size, and they can fill up more than one cell.

Figure 20-6 GridBagLayout

GridBagLayout

GridBagLayout determines the placement of its components based on each component's constraints and minimum size, plus the container's preferred size.

In the following discussion:

  • A component's cell refers to the entire set of grid cells the component occupies.

  • A component's display area refers to all the space of the cell that it occupies which is not taken up by the component's external padding (insets).

While GridBagLayout can accommodate a complex grid, it will behave more successfully (and more predictably) if you organize your components into smaller panels, nested inside the GridBagLayout container. These nested panels can use other layouts, and can contain additional panels of components if necessary. This method has two advantages:

  • It gives you more precise control over the placement and size of individual components because you can use more appropriate layouts for specific areas, such as button bars.

  • It uses fewer cells, simplifying the GridBagLayout and making it much easier to control.

On the other hand, GridBagLayout requires more containers, and therefore your program uses more memory, than if you used other layout managers.

20.5.9.1 Understanding GridBagLayout Constraints

GridBagLayout uses a GridBagConstraints object to specify the layout information for each component in a GridBagLayout container. Since there is a one-to-one relationship between each component and GridBagConstraints object, you need to customize the GridBagConstraints object for each of the container's components.

GridBagLayout components have the following constraints:

  • anchor

  • fill

  • gridx, gridy

  • gridwidth, gridheight

  • ipadx, ipady

  • weightx, weighty

GridBagConstraints give you control over:

  • The position of each component, absolute or relative.The size of each component, absolute or relative.

  • The number of cells each component spans.

  • How each cell's unused display area gets filled.

  • The amount of internal and external padding for each component.

  • How much weight is assigned to each component to control which components utilize extra available space. This controls the component's behavior when resizing the container.

For a detailed explanation of each of the constraints, including tips for using them and setting them in the Java Visual Editor, see the individual constraint topics.

20.5.9.2 Setting GridBagConstraints Manually in the Source Code

When you use the Java Visual Editor to design a GridBagLayout container, JDeveloper always creates a new GridBagConstraints2 object for each component you add to the container. GridBagConstraints is derived from GridBagConstraints , and has a constructor that takes all eleven properties of GridBagConstraints so the code generated by the Java Visual Editor can be simpler.

For example:

bevelPanel1.add(textFieldControl3, new GridBagConstraints2(0, 5, 6, 2, 1.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 0, 0), 150, 0));
bevelPanel1.add(checkboxControl1, new GridBagConstraints2(7, 5, 4, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(8, 29, 0, 24), 18, -11)); 

You can modify the parameters of the GridBagConstraints2 constructor directly in the source code, or you can use the Constraints property editor to change the values.

When you create a GridBagLayout container by coding it manually, you only need to create one GridBagConstraints object for each GridBagLayout container. GridBagLayout uses the GridBagConstraints default values for the component you add to the container, or it reuses the most recently modified value. If you want the component you're adding to the container to have a different value for a particular constraint, then you only need to specify the new constraint value for that component. This new value will stay in effect for subsequent components unless, or until, you change it again.

Note:

While this method of coding GridBagLayout is the leanest (recycling constraint values from previously added components), it doesn't allow you to edit that container visually in the Java Visual Editor.

20.5.9.3 Modifying Existing GridBagLayout Code to Work in the Java Visual Editor

If you have a GridBagLayout container that was previously coded manually by using one GridBagConstraints object for the container, you will not be able to edit that container in the Java Visual Editor without making the following modifications to the code:

  • You must create a GridBagConstraints2 object for each component added to the container.

  • The GridBagConstraints2 object must have a large constructor with parameters for each of the eleven constraint values, as shown above.

20.5.9.4 Designing GridBagLayout Visually in the Java Visual Editor

GridBagLayout is a complex but useful layout manager. JDeveloper has additional features in the Java Visual Editor that make GridBagLayout much easier to design and control, such as a Constraints property editor, a grid, and a pop-up menu on selected components.

There are two approaches you can take to designing GridBagLayout in the Java Visual Editor. You can design it from scratch by adding components to a GridBagLayout panel, or you can prototype the panel in the Java Visual Editor using another layout first, such as XYLayout, then convert it to GridBagLayout when you have all the components arranged and sized the way you want them. This method can speed up your design work substantially.

Whichever method you use, it is recommended that you take advantage of using nested panels (for more information, see Section 20.5.33, "Working with Nested Containers and Layouts") to group the components, building them from the inside out. Use these panels to define the major areas of the GridBagLayout container to simplify your GridBagLayout design, which gives you fewer cells in the grid and fewer components that need GridBagConstraints.

20.5.10 Converting to GridBagLayout

When you prototype your layout in another layout first, the conversion to GridBagLayout will be much cleaner and easier if you are careful about the alignment of the panels and components as you initially place them, especially left and top alignment. Keep in mind that you are actually designing a grid, so try to place the components inside an imaginary grid, and use nested panels to keep the number of rows and columns as small as possible. Using XYLayout for prototyping gives you the advantage of component alignment functions on the components' popup menu (accessed by right-clicking a component in the Java Visual Editor).

As the Java Visual Editor converts the design to GridBagLayout, it assigns constraint values for the components based on where the components were before you changed the container to GridBagLayout. Often, only minor adjustments are necessary, if any.

Converting to GridBagLayout assigns weight constraints to certain types of components (those which you would normally expect to increase in size as the container is enlarged at runtime, such as text areas, fields, group boxes, or lists). If you need to make adjustments to your design after converting to GridBagLayout, you'll find the task much easier if you remove all the weight constraints from any components first (set them all to zero).

If even one component has a weight constraint value greater than zero, it is hard to predict the sizing behavior in the Java Visual Editor due to the complex interactions between all the components in the container.

You can easily spot a GridBagLayout whose components have weights because the components will not be clustered together in the center of the container. Instead, the components fill the container to its edges.

Tip:

When you remove all the weights from the components in a GridBagLayout, one of two things will happen:
  • If the container is large enough for the grid, the components will all cluster together in the center of the container, with any extra space around the edges of the grid.

  • If the container is too small for the components, the grid will expand beyond the edges of the container and the components that are off the edges of the container will be invisible. Enlarge the size of the container until all the components fit. If the GridBagLayout container you are designing is a single panel in the center of the main UI frame, enlarge the size of the frame. You can resize this container to the final size after you have finished setting all the components' constraints.

20.5.11 Adding Components to a GridBagLayout Container

If you want to create your GridBagLayout by starting out with a new GridBagLayout container and adding all the components to it from scratch, there are certain behaviors you should expect.

  • Since the default weight constraint for all components is zero, when you add the first component to the container, it will locate to the center of the container at its minimumSize. You will now have a grid with one row and one column.

  • The next component you add will be placed in an adjacent cell, depending on where you click. If you click under the first component, it will go on the next row in that column. If you click to the right of the component, it will go on the same row in the next column. All subsequent components are added the same way, increasing the number of cells by one as you add each one.

  • Once you have several components, or cells containing components, you can use the mouse to drag the components to new cell locations, or you can change the gridx and gridy constraints in the Constraints property editor.

  • No matter how many components you add, as long as the grid stays smaller than the container, they will all cluster together in the middle of the container. If you need a bigger container, simply enlarge it in the Java Visual Editor.

  • If after several rows, your design has been fitting nicely into a certain number of columns, then you suddenly have a row that requires an odd number of components, consider dropping a panel into that row that takes up the entire row, and use a different layout inside that panel to achieve the look you want.

20.5.12 How to Set GridBagConstraints in the Constraints Property Editor

By using the GridBagLayout Constraints property editor, some of the GridBagConstraints can be specified in the Java Visual Editor without having to edit the source code.

Figure 20-7 Constraints Editor

Constraints Editor

One big advantage to using the Constraints property editor for setting constraints is the ability to change constraints for multiple components at the same time. For example, if you want all the buttons in your GridBagLayout container to use the same internal padding, you can hold down the Shift key while you select each one, then open the Constraints property editor and edit the constraint.

To use the Constraints property editor:

  1. Select the component(s) within the GridBagLayout container you want to modify, either in the Structure window or in the Java Visual Editor.

  2. Select the constraints property in the Property Inspector and click its value field.

  3. Set the desired constraints in the property editor, then press OK.

20.5.13 Displaying the Grid

The Java Visual Editor displays an optional grid that lets you see exactly what is happening with each cell and component in the layout.

  • To display this grid, right-click on a component in the GridBagLayout container and select Show Grid.

  • To hide the grid temporarily when Show Grid is selected, click on a component that is not in the GridBagLayout container (including the GridBagLayout container itself) and the grid will disappear. The grid is only visible when a component inside a GridBagLayout container is selected.

  • To hide the grid permanently, right-click a component and select Show Grid again.

20.5.14 Using the Mouse to Change Constraints

The Java Visual Editor allows you to use the mouse for setting some of the constraints by dragging the whole component or by grabbing various sizing nibs on the component. Directions for setting constraints visually are included in the individual following constraint topics.

20.5.15 Using the GridBagLayout Popup Menu

Right-clicking a GridBagLayout component displays a context menu that gives you easy access to some of the properties of the Constraints property editor, and lets you quickly set or remove certain constraints.

Table 20-4 GridBagLayout Popup Menu Commands

Menu Command Action

Remove Padding

Sets any size padding values (ipadx and ipady) for the selected component to zero.

Constraints...

Displays the Constraints popup editor for the selected GridBagLayout component.

Fill Horizontal

Sets (ors) the fill constraint value for the component to HORIZONTAL. The component expands to fill the cell horizontally. If the fill was VERTICAL, it sets the constraint to BOTH.

Fill Vertical

Sets (ors) the fill constraint value for the component to VERTICAL. The component expands to fill the cell vertically. If the fill was HORIZONTAL, it sets the constraint to BOTH.

Remove Fill

Changes the fill constraint value for the component to NONE.

Weight Horizontal

Sets the weightx constraint value for the component to 1.0.

Weight Vertical

Sets the weighty constraint value for the component to 1.0

Remove Weights

Sets both weighty and weighty constraint values for the component to 0.0.


20.5.16 GridBagConstraints

The following section lists each of the GridBagConstraints separately. It defines each one, explaining its valid and default values, and tells you how to set that constraint visually in the Java Visual Editor.

anchor

When the component is smaller than its display area, use the anchor constraint to tell the layout manager where to place the component within the area.

The anchor constraint only affects the component within its own display area, depending on the fill constraint for the component. For example, if the fill constraint value for a component is GridBagConstraints.BOTH (fill the display area both horizontally and vertically), the anchor constraint has no effect because the component takes up the entire available area. For the anchor constraint to have an effect, set the fill constraint value to GridBagConstraints.NONE, GridBagConstraints.HORIZONTAL , or GridBagConstraints.VERTICAL.

Valid values:

GridBagConstraints.CENTER

GridBagConstraints.NORTH

GridBagConstraints.NORTHEAST

GridBagConstraints.EAST

GridBagConstraints.SOUTHEAST

GridBagConstraints.SOUTH

GridBagConstraints.WESTGridBagConstraints.SOUTHWEST

GridBagConstraints.NORTHWEST

Default Value: GridBagConstraints.CENTER

To set the anchor constraint in the Java Visual Editor:

You can use the mouse to set the anchor for a component that is smaller than its cell. Simply click on the component and drag it, dragging the component toward the desired location at the edge of its display area, much like you would dock a movable toolbar. For example, to anchor a button to the upper left corner of the cell, click the mouse in the middle of the button, and drag it until the upper left corner of the button touches the upper left corner of the cell. This sets the anchor constraint value to NorthWest.

You can also specify the anchor constraint in the Constraints property editor:

  1. Select the component in the Java Visual Editor.

  2. In the Property Inspector click the constraints property to display the Constraints editor.

  3. Select the desired anchor constraint value in the Anchor area, then press OK.

fill

When the component's display area is larger than the component's requested size, use the fill constraint to tell the layout manager which parts of the display area should be given to the component. As with the anchor constraint, the fill constraint only affects the component within its own display area. Fill tells the layout manager to expand the component to fill the whole area it has been given.

Valid values:

GridBagConstraints.NONE

(Don't change the size of the component.)

GridBagConstraints.BOTH

(Resize the component both horizontally and vertically to fill the area completely.)

GridBagConstraints.HORIZONTAL

(Only resize the component to fill the area horizontally.)

GridBagConstraints.VERTICAL

(Only resize the component to fill the area vertically.)

Default Value: GridBagConstraints.NONE

To specify the fill constraint in the Java Visual Editor:

The fastest way to specify the fill constraint for a component is to use the component's context menu in the Java Visual Editor.

  1. Right-click the component in the Java Visual Editor to display the context menu.

  2. Do one of the following:

    • Select Fill Horizontal to set the value to HORIZONTAL.

    • Select Fill Vertical to set the value to VERTICAL.

    • Select both Fill Horizontal and Fill Vertical to set the value to BOTH.

    • Select Remove Fill to set the value to NONE.

    You can also specify the fill constraint in the Constraints editor.

    1. In the Property Inspector click the constraints property to display the Constraints editor.

    2. Select the desired fill constraint value in the Fill area, then press OK.

gridwidth, gridheight

Use these constraints to specify the number of cells in a row (gridwidth) or column (gridheight) the component uses. This constraint value is stated in cell numbers, not in pixels.

Valid values:

gridwidth=nn, gridheight=nn

(Where nn is an integer representing the number of cell columns or rows.)

GridBagConstraints.RELATIVE (-1)

Specifies that this component is the next to last one in the row (gridwidth) or column (gridheight.) A component with a GridBagConstraints.RELATIVE takes all the remaining cells except the last one. For example, in a row of six columns, if the component starts in the third column, a gridwidth of RELATIVE will make it take up columns three, four, and five.

GridBagConstraints.REMAINDER (0)

Specifies that this component is the last one in the row (gridwidth) or column (gridheight).

Default Value: gridwidth=1, gridheight=1

To specify gridwidth and gridheight constraints in the Java Visual Editor:

You can specify gridwidth and gridheight constraint values in the Constraints property editor.

  1. In the Property Inspector click the constraints property to display the Constraints editor.

  2. In the Grid Position area, enter a value for gridwidth in the Width field, or a value for gridheight in the Height field. Specify the number of cells the component will occupy in the row or column.

    • If you want the value to be RELATIVE, enter a -1.

    • If you want the value to be REMAINDER, enter a 0.

You can use the mouse to change the gridwidth or gridheight by sizing the component into adjacent empty cells.

gridx, gridy

Use these constraints to specify the grid cell location for the upper left corner of the component. For example, gridx=0 is the first column on the left, and gridy=0 is the first row at the top. Therefore, a component with the constraints gridx=0 and gridy=0 is placed in the first cell of the grid (top left).

GridBagConstraints.RELATIVE specifies that the component be placed relative to the previous component as follows:

  • When used with gridx, it specifies that this component be placed immediately to the right of the last component added.

  • When used with gridy, it specifies that this component be placed immediately below the last component added.

Valid values:

gridx=nn, gridy=nn

GridBagConstraints.RELATIVE (-1)

A maximum value of 512 rows and columns is supported by GridBagLayout; therefore, values you specify for X and Y must be not exceed 512.

Default value:

gridx=0, gridy=0

To specify the grid cell location in the Java Visual Editor:

You can use the mouse to specify which cell the upper left corner of the component will occupy. Click near the upper left corner of the component and drag it into a new cell. When moving components that take up more than one cell, be sure to click in the upper left cell when you grab the component. Sometimes, due to existing values of other constraints for the component, moving the component to a new cell with the mouse may cause changes in other constraint values, for example, the number of cells that the component occupies might change. To more precisely specify the gridx and gridy constraint values without accidentally changing other constraints, use the Constraints property editor.

  1. In the Property Inspector click the constraints property to display the Constraints editor.

  2. In the Grid Position area, enter the column number for gridx value in the X field, or the row number for gridy value in the Y field. If you want the value to be RELATIVE, enter a -1.

Note:

When you use the mouse to move a component to an occupied cell, the Java Visual Editor ensures that two components never overlap by inserting a new row and column of cells so the components will not be on top of each other. When you relocate the component using the Constraints property editor, the Java Visual Editor does not check to make sure the components don't overlap.

insets

Use insets to specify the minimum amount of external space (padding) in pixels between the component and the edges of its display area. The inset says that there must always be the specified gap between the edge of the component and the corresponding edge of the cell. Therefore, insets work like brakes on the component to keep it away from the edges of the cell. For example, if you increase the width of a component with left and right insets to be wider than its cell, the cell will expand to accommodate the component plus its insets. fill and padding constraints never steal any space from insets.

Valid values:

insets = new Insets(n,n,n,n)

Top, left, bottom, right (where each parameter represents the number of pixels between the display area and one edge of the cell).

Default values:

insets = new Insets(0,0,0,0)

To set inset values in the Java Visual Editor:

The Java Visual Editor displays blue sizing nibs on a selected GridBagLayout component to indicate the location and size of its insets. Grab a blue nib (sizing handle) with the mouse and drag it to increase or decrease the size of the inset.

When an inset value is zero, you will only see one blue nib on that side of the cell, as shown in Figure 20-8.

Figure 20-8 GridBagLayout with Inset Value Set to 0

GridBagLayout with Inset Value Set to 0

As shown in Figure 20-9, when an inset value is greater than zero, the Java Visual Editor displays a pair of blue nibs for that inset: one on the edge of the cell and one on the edge of the display area. The size of the inset is the distance (number of pixels) between the two nibs. Grab either nib to change the size of the inset.

Figure 20-9 GridBagLayout with Inset Value Set to Greater Than 0

GridBagLayout with Inset Value Set to Greater Than 0

For more precise control over the inset values, use the Constraints property editor to specify the exact number of pixels.

  1. In the Property Inspector click the constraints property to display the Constraints editor.

  2. In the External Insets area, specify the number of pixels for each inset: top, left, bottom, or right.

Note:

Although negative inset values are legal, they can cause components to overlap adjacent components, and are not recommended.

ipadx, ipady

These constraints specify the internal padding for a component. Use ipadx and ipady to specify the amount of space (in pixels) to add to the minimum size of the component for internal padding. For example, the width of the component will be at least its minimum width plus ipadx in pixels. The code only adds it once, splitting it evenly between both sides of the component. Similarly, the height of the component will be at least the minimum height plus ipady pixels.

  1. ipadx specifies the number of pixels to add to the minimum width of the component.

  2. ipady specifies the number of pixels to add to the minimum height of the component.

For example, when added to a component that has a preferred size of 30 pixels wide and 20 pixels high:

  • If ipadx= 4, the component will be 34 pixels wide

  • If ipadx= 2, the component will be 22 pixels high.

Valid values:

ipadx=nn, ipadx=nn

Default value:

ipadx=0, ipady=0

To set the size of internal padding constraints in the Java Visual Editor:

Setting the size of internal padding constraints in the Java Visual Editor. If you drag the sizing nib beyond the edge of the cell into an empty adjacent cell, the component will occupy both cells (the gridwidth or gridheight values will increase by one cell).

Figure 20-10 Before Dragging the Sizing Nib Beyond the Edge of a Cell

Before Dragging the Sizing Nib Beyond the Edge of a Cell

Figure 20-11 After Dragging the Sizing Nib Beyond the Edge of a Cell

After Dragging the Sizing Nib Beyond the Edge of a Cell

For more precise control over the padding values, use the Constraints property editor to specify the exact number of pixels to use for the value.

  1. In the Property Inspector click the constraints property to display the Constraints editor.

  2. Enter the number of pixels for the Width and Height values in the Size Padding area, then press OK.

To quickly remove the padding (set it to zero), right-click the component in the Java Visual Editor and choose Remove Padding. You can also select multiple components and use the same procedure to remove the padding from all of them at once.

Negative values are valid. They will make the component smaller than its preferred size.

Note:

Padding, much like XYLayout, may not be accurate on different computer systems or in different languages.

weightx, weighty

Use the weight constraints to specify how to distribute a GridBagLayout container's extra space horizontally (weightx) and vertically (weighty) when the container is resized. Weights determine what share of the extra space gets allocated to each cell and component when the container is enlarged beyond its default size.

Weight values are of type double and are specified numerically in the range 0.0 to 1.0 inclusive. Zero means the component should not receive any of the extra space, and 1.0 means the component gets a full share of the space.

  • The weight of a row is calculated to be the maximum weightx of all the components in the row.

  • The weight of a column is calculated to be the maximum weighty of all the components in the column.

Valid Values:

weightx=n.n, weighty=n.n

Default Value:

weightx=0.0, weighty=0.0

To set weightx and weighty constraints in the Java Visual Editor:

To specify the weight constraints for a component in the Java Visual Editor, right-click the component and choose Weight Horizontal (weightx), or Weight Vertical (weighty). This sets the value to 1.0. To remove the weights (set them to zero), right-click the component and choose Remove Weights. You can do this for multiple components: hold down the Shift key when selecting the components, then right-click and choose the appropriate menu item.

If you want to set the weight constraints to something other than 0.0 or 1.0, you can set the values in the Constraints editor.

  1. In the Property Inspector click the constraints property to display the Constraints editor.

  2. Enter a value between 0.0 and 1.0 for the X (weightx) or Y (weighty) value in the Weight area, then press OK.

Note:

Because weight constraints can make the sizing behavior in the Java Visual Editor difficult to predict, setting these constraints should be the last step in designing a GridBagLayout.

Examples of How Weight Constraints Affect Components' Behavior

  • As shown inFigure 20-12, if all the components have weight constraints of zero in a single direction, the components will clump together in the center of the container for that dimension and won't expand beyond their preferred size. GridBagLayout puts any extra space between its grid of cells and the edges of the container.

    Figure 20-12 Weight Constraints Set to Zero

    Weight Constraints Set to Zero
  • As shown inFigure 20-13, if you have three components with weightx constraints of 0.0, 0.3, and 0.2 respectively, when the container is enlarged, none of the extra space will go to the first component, 3/5 of it will go the second component, and 2/5 of it will go to the third.

    Figure 20-13 Three Components with Weight Constraints Set to 0.0, 0.3, and 0.2

    Components with Constraints Set to 0.0, 0.3, and 0.2
  • You need to set both the weight and fill constraints for a component if you want it to grow. For example, if a component has a weightx constraint, but no horizontal fill constraint, then the extra space goes to the padding between the left and right edges of the component and the edges of the cell. It enlarges the width of the cell without changing the size of the component. If a component has both weight and fill constraints, then the extra space is added to the cell, plus the component expands to fill the new cell dimension in the direction of the fill constraint (horizontal in this case).

    In Figure 20-14, all the components in the GridBagLayout panel have a weight constraint value of zero. Because of this constraint, the components are clustered in the center of the GridBagLayout panel, with all the extra space in the panel distributed between the outside edges of the grid and the panel. The size of the grid is determined by the preferred size of the components, plus any insets and padding (ipadx or ipady).

    Figure 20-14 All Components with Weight Constraint Value Set to Zero

    All Components with Weight Constraint Value Set to Zero

    In Figure 20-15, a horizontal weight constraint of 1.0 is specified for the ListControl. Notice that as soon as one component is assigned any weight, the UI design is no longer centered in the panel. Since a horizontal weight constraint was used, the GridBagLayout manager takes the extra space in the panel that was previously on each side of the grid, and puts it into the cell containing the ListControl. Also notice that the ListControl did not change size.

    Figure 20-15 Horizontal Weight Constraint Set to 1.0 For ListControl.

    Horizontal Weight Constraint Set to 1.0 For ListControl.

    Tip:

    f there is more space than you like inside the cells after adding weight to the components, decrease the size of the UI frame until the amount of extra space is what you want. To decrease the size of the frame, select the frame in the Java Visual Editor or the Structure window, this(BorderLayout), then click its black sizing nibs and drag the frame to the desired size.

    As shown in Figure 20-16, if a horizontal fill is then added to the ListControl, the component expands to fill the new horizontal dimension of the cell.

    Figure 20-16 Horizontal Fill Added to ListControl

    Horizontal Fill Added to ListControl
  • If one component in a column has a weightx value, GridBagLayout gives the whole column that weight. Conversely, if one component in a row has a weighty value, the whole row is assigned that weight.

20.5.17 Using OverlayLayout2

OverlayLayout2 arranges components over the top of each other. The requested size of the container will be the largest requested size of the children, taking alignment needs into consideration. The alignment is based upon what is needed to properly fit the children in the allocation area. The children will be placed such that their alignment points are all on top of each other. Unlike BorderLayout's centering, OverlayLayout2 does not expand the component to fill the available space, but instead leaves it at its preferred size.

20.5.18 Using PaneLayout

As shown in Figure 20-17, PaneLayout allows you to specify the size of a component in relation to its sibling components. PaneLayout applied to a panel or frame lets you control the percentage of the container the components will have relative to each other, but does not create moveable splitter bars between the panes.

Figure 20-17 PaneLayout

PaneLayout

In a PaneLayout, the placement and size of each component is specified relative to the components that have already been added to the container. Each component specifies a PaneConstraints object that tells the layout manager from which component to take space, and how much of its existing space to take. Each component's PaneConstraints object is applied to the container as it existed at the time the component was added to the container. The order in which you add the components to the container is very important.

The constraint for a PaneConstraints component that is being added to a container consists of four variables:

  • String name

    The name for this component (must be unique for all components in the container - as in CardLayout).

  • String splitComponentName

    The name of the component from which space will be taken to make room for this component.

  • String position

    The edge of the splitComponentName to which this component will be anchored.

    Table 20-5 shows valid values.

    Table 20-5 Valid values for String position

    Select this To do this

    PaneConstraints.TOP

    This component will be above splitComponentName.

    PaneConstraints.BOTTOM

    This component will be below splitComponentName.

    PaneConstraints.RIGHT

    This component will be to the right of splitComponentName.

    PaneConstraints.LEFT

    This component will be to the left of splitComponentName.

    PaneConstraints.ROOT

    This component is the first component added.


  • float proportion

    The proportion of splitComponentName that will be allocated to this component. A number between 0 and 1.

20.5.19 How Components are Added to PaneLayout

Components are added to PaneLayout as follows:

  • The first component will always take all the area of the container. The only important variable in its PaneConstraint is its name. Other components will use this value, specifying it as their splitComponentName.

  • The second component must specify its splitComponentName as the name of the first component.

  • The splitComponentName of subsequent components may be the name of any component that has already been added to the container.

20.5.20 How to Create a PaneLayout Container in the Java Visual Editor

You can create a PaneLayout container in the Java Visual Editor.

To create a PaneLayout Container:

  1. Add a container to your UI in the Java Visual Editor. This can be any kind of a frame or panel, such as the one shown in Figure 20-18.

    Figure 20-18 UI Container in Java Visual Editor

    UI Container in Java Visual Editor
  2. Change the container's layout property to PaneLayout. This allows you to access the PaneLayout properties in the Inspector.

  3. From the Component Palette, select the first component and drop it into the PaneLayout container. This component will completely fill the container until you add another component.

    Figure 20-19 Component Dropped in PaneLayout Container

    Component Dropped in PaneLayout Container
  4. Select the second component and drag it to the desired size in the desired position.

    Figure 20-20 Second Component Dragged into PaneLayout

    Second Component Dragged into PaneLayout

    Note:

    f the first component you added to a PaneLayout container was itself a container, the Java Visual Editor assumes you are trying to add the second component to the outer container instead of to the PaneLayout container. Use the component tree to specify to the containers that you want the component to be placed in.
  5. To add a third component to the PaneLayout, draw it similarly to define its position relative to the other components.

    For example, to split the right half of the container, begin drawing the third component starting from the middle of the right edge of the panel to the bottom right corner of the first component.

    Figure 20-21 Third Component Dragged into PaneLayout

    Third Component Dragged into PaneLayout
  6. Use the same method to add subsequent components.

20.5.21 Using VerticalFlowLayout

VerticalFlowLayout arranges components in columns from top to bottom, then left to right using each component's preferredSize. VerticalFlowLayout lines up as many components as it can in a column, then moves to a new column. Typically, VerticalFlowLayout is used to arrange buttons on a panel.

Figure 20-22 VerticalFlowLayout

VerticalFlowLayout

You can choose how to arrange the components in the columns of a VerticalFlowLayout container by specifying an alignment justification of top, middle, or bottom. You can also specify the amount of gap (horizontal and vertical spacing) between components and columns. It also has properties that let you specify the components should fill the width of the column, or the last component should fill the remaining height of the container. Use the Inspector to change these properties when you're in the Java Visual Editor.

Alignment

  • TOP - groups the components at the top of the container.

  • MIDDLE - centers the components vertically in the container.

  • BOTTOM - groups the components so the last component is at the bottom of the container.

The default alignment in a VerticalFlowLayout is MIDDLE.

To change the alignment, select the verticalFlowLayout object in the Structure window, then specify a value in the Inspector for the alignment property as follows:

  • 0=TOP

  • 1=Middle

  • 2=BOTTOM

Gap

The default gap between components in a VerticalFlowLayout is 5 pixels.

To change the horizontal or vertical gap, select the VerticalFlowLayout object in the Structure window, then modify the pixel value of the hgap (horizontal gap) or vgap (vertical gap) property in the Inspector.

Order of Components

To change the order of the components in a VerticalFlowLayout container, drag the component to the new location.

Horizontal Fill

horizontalFill lets you specify a fill to edge flag which causes all the components to expand to the container's width.

Figure 20-23 horizontalFill

horizontalFill

WARNING:

Your program can become unstable if the main panel has less space than it needs. This property also prohibits multi-column output.

Vertical fill

verticalFill lets you specify a vertical fill flag that causes the last component to fill the remaining height of the container.

Figure 20-24 verticalFill

verticalFill

The default value for verticalFill is False.

20.5.22 Using XYLayout

XYLayout is a JDeveloper custom layout manager. XYLayout puts components in a container at specific (x,y) coordinates relative to the upper left corner of the container. Regardless of the type of display, the container will always retain the relative (x,y) positions of components. However, when you resize a container with an XYLayout, the components do not reposition or resize.

For XYLayout containers, the preferredSize of the container is defined by the values specified in the width and height properties of the XYLayout. For example, if you have the following lines of code in your container initialization,

xYLayoutN.setWidth(400);

xYLayoutN.setHeight(300);

and if xYLayoutN is the layout manager for the container, then its preferredSize is 400 x 300 pixels.

If one of the nested panels in your UI uses XYLayout, that panel's preferredSize will be determined by the layout's setWidth() and setHeight() calls. This value will be used for the panel in computing the preferredSize of the next (outer) container.

Figure 20-25 XYLayout

XYLayout

You'll discover that XYLayout is very convenient to use in prototyping a user interface. When you design more complicated user interfaces with multiple nested panels, XYLayout can be used for the initial layout of the panels and components, after which you can choose from one of the standard layouts for the final design.

Note:

XYLayout uses absolute x,y values when positioning objects on the screen, and does not adjust to different screen resolutions. To ensure your layout adjusts to other resolutions, don't leave any containers in XYLayout in your final design.

You can use the UI design tools to specify the container's size and its components' x,y coordinates.

  • To specify the size of a container using XYLayout, select the XYLayout object in the Structure window and enter the pixel dimension for the height and width properties in the Property Inspector. This setting specifies the size of the XYLayout container.

  • To change the (x,y) values for a container using XYLayout, do one of the following:

    • In the Java Visual Editor, drag the component to a new size. JDeveloper automatically updates the constraint values in the Property Inspector.

    • Select the component in the Structure window, then click the constraints property edit field and enter coordinates for that component.

    the alignment options available from the context menu.

    Table 20-6 Alignment Options

    Select this To do this

    Move to first

    Moves the selected component to the top of the Z-order.

    Move to last

    Moves the selected component to the bottom of the Z-order.

    Align left

    Lines up the left edges of the selected components with the left edge of the first selected component.

    Align center

    Horizontally lines up the centers of the selected components with the center of the first selected component.

    Align right

    Lines up the right edges of the selected components with the right edge of the first selected component.

    Align top

    Lines up the top edges of the selected components with the top edge of the first selected component.

    Align middle

    Vertically lines up the centers of the selected components with the middle of the first selected component.

    Align bottom

    Lines up the bottom edges of the selected components with the bottom edge of the first selected component.

    Even space horizontal

    Evenly spaces the selected components horizontally between the first and last selected components.

    Even space vertical

    Evenly spaces the selected components vertically between the first and last selected components.

    Same size horizontal

    Makes all the selected components the same width as the first selected component.

    Same size vertical

    Makes all the selected components the same height as the first selected component.


    A simpler approach to XYLayout is to prototype the UI directly in the Java Visual Editor by setting the layout to null. UI components are set where you place them at the size you create them. For more information, see Section 20.6, "Prototyping Your UI with Layout Properties".

20.5.23 Understanding Layout Properties

Each container normally has some kind of layout manager attached to its layout property. The layout manager has properties that can affect the sizing and location of all components that are added to the container. You can view and edit these properties in the Inspector when the layout manager is selected in the Structure window. The layout manager displays as an item in the Structure window just below the container to which it is attached.

Figure 20-26 Layout Properties

Layout Properties

20.5.24 Understanding Layout Constraints

For each component you add to a container, JDeveloper may instantiate a constraints object, or produce a constraint value, which provides additional information about how the layout manager should size and locate this specific component. The type of constraint object or value created depends upon the type of layout manager being used. The Inspector displays the constraints of each component as if they were properties of the component itself, and allows you to edit them.

20.5.25 Determining the Size and Location of Your UI Window at Runtime

If your UI class is a Frame or Dialog, you can control its size and location at runtime. The size and location are determined by what the code does when the UI window is created and what the user does to resize or reposition it.

When the UI window is created, and various components are added to it, each component that is added affects the preferredSize of the overall window, typically making the preferredSize of the window container larger as additional components are added. This effect on preferredSize depends on the layout manager of the outer container, as well as any nested container layouts. For more details about the way that preferredLayoutSize is calculated for various layouts, see the sections in this document on each type of layout.

The size of the UI window, as set by your program (before any additional resizing that may be done by the user), is determined by which of the following container methods is called last in the code:

  • pack()

  • setsize()

The location of your UI at runtime will be at 0,0 unless you override this by setting the location property of the container (for example by calling setLocation() before making it visible).

20.5.26 Sizing a Window Automatically with pack()

The pack() method computes a window's preferredSize, based upon the components it contains, and sizes itself accordingly. pack() creates the smallest possible window, while still respecting the preferredSize of the components that are placed within it.

Note:

The Application.java file created by the New Application dialog calls pack(), packing the frame to its preferredSize before making it visible.

20.5.27 How the preferredSize is Calculated for a Container

preferredSize is calculated differently for containers with different layouts

20.5.28 Portable Layouts

Portable layouts, such as FlowLayout and BorderLayout, calculate their preferredSize based on a combination of the layout rules and the preferredSize of each component that was added to the container. If any of the components are containers (such as a Panel), then the preferredSize of that Panel is calculated according to its layout and components. The layout calculation is recursed into as many layers of nested containers as necessary. For more information about preferredSize calculation for particular layouts, see the individual layout descriptions.

20.5.29 Explicitly Setting the Size of a Window Using setSize()

If you call setSize() on the container (rather than pack() or subsequent to calling pack()), the size of the container will be set to a specific size, in pixels. setSize() overrides the effect of pack() and preferredSize for the container.

Note:

Because different screens have different pixel sizes, if you use setSize() you must call validate() in order for child containers to be properly laid out. Note that pack() automatically calls validate().

20.5.30 Making the Size of your UI Portable to Various Platforms

To make your UI portable, either use pack() or calculate an appropriate size to use with setSize() based on the pixel sizes of the various screens your application will be deployed on.

For example, you might want the UI to appear at 75% of the width and height of the screen. For the UI to appear at this sizing, you can add the following lines of code to your application class instead of calling pack():

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize.width * 3 / 4, screenSize.height * 3 / 4); 

Note:

To ensure portability, change all XYLayout containers to a portable layout after prototyping. For more information, see Section 20.6, "Prototyping Your UI with Layout Properties".

20.5.31 Positioning a Window on the Screen

If you don't explicitly position your UI, it will appear in the upper left corner of the screen.

To center the UI on the screen, obtain the width and height of the screen, subtract the width and height of your UI, divide the difference by two (in order to create equal margins on opposite sides of the UI), and use these figures for the location of the upper left corner of your UI.

The code in Example 20-1 is generated when you select the Center Frame on Screen option in the New Application dialog, and performs this calculation for you.

Example 20-1 Code Generated When You Select Center Frame on Screen Option

//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
Dimension frameSize = frame.getSize(); 
if (frameSize.height > screenSize.height) 
  frameSize.height = screenSize.height;
if (frameSize.width > screenSize.width) 
  frameSize.width = screenSize.width; 
frame.setLocation((screenSize.width- frameSize.width) / 2, 
(screenSize.height - frameSize.height) /2); 

20.5.32 Placing the Sizing and Positioning Method Calls in your Code

The calls to pack(), validate(), setSize(), or setLocation() can be made from inside the UI container class for example, this.pack(). These calls can also be made from the class that creates the container, for example, frame.pack(), after invoking the constructor, before setVisible(). The latter is what the New Application dialog-generated code does; the calls to pack() or validate(), and setLocation() are placed in the Application class, after the frame is constructed (after the call to jbInit()).

If you are constructing the UI from various places within your application, and you want it to come up in the same size and place, place your calls in the constructor of your UI container class (after the call to jbInit(). If your application instantiates the UI from only one place, such as in the New Application dialog generated application, put the sizing and positioning code in the place where the UI is created, in this case the Application class.

20.5.33 Working with Nested Containers and Layouts

Most UI designs in Java use more than one type of layout to get the desired component positions by nesting multiple panels with different layouts in the main container. By creating a composite design, and by using the appropriate layout manager for each panel, you can group and arrange components in a way that is both functional and portable.

For example, Figure 20-27 demonstrates the use of nested panels with different layouts. The solid gray objects are the buttons and other visible components in the UI which are nested in various levels of panels.

Figure 20-27 Nested Panels

Nested Panels

20.5.33.1 How to Create Nested Panels

You can nest panels within other panels to gain more control over the placement of components.

To create nested panels:

  1. Add a panel to the UI design of your application. For more information, see Section 20.7.9, "How to Create a Panel."

  2. In the Property Inspector, change the Layout property to null.

    When you add a panel to the UI design, it uses FlowLayout. Change the layout to null initially because it is the easiest layout to work with during the design process. After you have all the panels and other components in place in your UI, you will set it to its final layout.

    To locate a specific panel in the Java Visual Editor, you can select the panel in the Structure window.

  3. Place panels within panels to logically group components.

    • Make sure components are fully nested inside their panels. Examine the Structure window to make sure each component is indented under the correct panel in the tree outline.

    • The components will probably be irregular sizes and shapes. Don't worry about getting it perfect at this point, because when you change the panel layouts, the layout manager will realign the components.

  4. Set the layout property for each panel to the appropriate layout. For more information, see Section 20.5.23, "Understanding Layout Properties."

    • Be aware that when you change a layout manager for one panel, the effects may change again when you change the layout manager for the panel that holds it.

    • Select the layout object in the Structure window to change its settings.

20.5.34 Adding Custom Layout Managers

JDeveloper supports the integration of other layout managers with its Java Visual Editor. Users will be able to work with the layout manager using both the Java Visual Editor and the Property Inspector when you:

  1. Write an oracle.jdevimpl.uieditor.LayoutAssistant implementation to be associated with the LayoutManager.

  2. Register the LayoutAssistant implementation with the IDE.

  3. (Optionally) Register a java.beans.PropertyEditor with the IDE to handle any special constraints type.

To create a custom layout manager assistant:

Each LayoutManager must be associated with a LayoutAssistant implementation. The class oracle.jdevimpl.uieditor.assistant.BasicLayoutAssistant provides a minimal implementation of the interface oracle.jdevimpl.uieditor.LayoutAssistant and will be used for any LayoutManager for which no explicit registration has been made. There are several required methods in the interface, but it is beyond the scope of this topic to describe them. Integrators may wish to subclass their LayoutAssistant implementations from this minimal implementation. Refer to the Javadoc for the LayoutAssistant interface for details.

To register the layout assistant:

To register the new layout assistant, you need to add a key-value definition to oracle.jdevimpl.uieditor.UIEditorAddin section in the JDeveloper\lib\addins.xml file as follows:

<property>
  <key>PREFIX.LAYOUT_MANAGER_CLASS_NAME</key>
  <value>LAYOUT_ASSISTANT_CLASS_NAME</value> 
</property> 

where:

  • PREFIX is jdeveloper.uiassistant

  • LAYOUT_MANAGER_CLASS_NAME is the fully-qualified classname of the layout manager for which an assistant is being registered

  • LAYOUT_ASSISTANT_CLASS_NAME is the fully-qualified classname of the layout manager assistant to register

For example, if you were to register a LayoutAssistant implementation oracle.jdevimpl.uieditor.assistant.GridBagLayoutAssistant for the java.awt.GridBagLayout layout manager, the property to add would look like:

<property>
  <key>jdeveloper.uiassistant.java.awt.GridBagLayout</key>
  <value>oracle.jdevimpl.uieditor.assistant.GridBagLayoutAssistant</value>
</property>

Note that in order for the layout assistant to be available from within the IDE, so that it will appear in the Property Inspector's layout property list, the layout assistant must be added to the IDEClasspath as a directive in JDeveloper\bin\jdev.conf file. For example:

AddJavaLibFile <myAssistant.jar>

where:

myAssistant.jar contains the compiled class file for your LayoutAssistant implementation.

To register a constraints property editor for the layout manager:

If your custom layout manager uses a constraint class, you may want to register a class implementing java.beans.PropertyEditor for editing the constraints. You register the property editor class under Inspector.PropertyEditor in the ide.properties file, where:

  • Inspector.PropertyEditor.count=# provides the total number of property editors that are registered in ide.properties. You must increment the count for each new property editor you wish to add.

  • <#> is the zero-based index, in the list of registered editors, corresponding to the editor you are registering.

  • <fully qualified type> is the fully-qualified type of the constraints for which a PropertyEditor is being registered.

  • <Fully qualified class> is the fully-qualified classname of the java.beans.PropertyEditor implementation being registered for editing instances of the given constraints type.

For example, if you were to register the property editor for the GridBagLayout layout manager's GridBagConstraints, your entry in the ide.properties file would look like:

Inspector.PropertyEditor.count=1

Inspector.PropertyEditor.editor1.type=java.awt.GridBagConstraints
Inspector.PropertyEditor.editor1.editor=oracle.jdevimpl.uieditor.assistant.GridBagConstraintsEditor 

Note:

Your property editor class also needs to be in the IDEClasspath as described above for the layout manager assistant.

20.6 Prototyping Your UI with Layout Properties

Before you start creating your UI, it is useful to sketch your UI design on paper to get an idea of the general strategy you'll use for placing various panels and components, and for assigning layouts. You can also prototype your UI directly in the Java Visual Editor. JDeveloper makes this easy by providing a layout called null that leaves the components where you place them at the size you create them.

20.6.1 Using null Layout for Prototyping

To make this approach simpler, JDeveloper provides the null layout. When you start a project using the New Application dialog, JDeveloper generates a UI container class (usually one that extends Frame or JFrame) that uses null. You can open the frame in the Java Visual Editor and do your design work directly on the frame.

When you initially add a new panel of any type to the Java Visual Editor, you'll notice that the layout property in the Inspector says <default layout>, which means that the Java Visual Editor will automatically use the default layout for that container. However, you may want to change the layout property to the layout manager you want to use so it is visible in the Structure window and that component constraints can be modified in the Property Inspector. You cannot edit layout properties for <default layout>.

20.6.2 Designing the Big Regions First

Design the big regions of your UI first, then, using null, work down into finer details within those regions. Once the design is right, work systematically from the inner regions outward, converting the panels to more portable layouts such as FlowLayout, BorderLayout, or GridLayout, making minor adjustments if necessary.

In most cases, you will place a container in your design first, then add components to it. You can also draw a new container around existing components. However, these components will not automatically nest into the new panel. After drawing the container, you must move each component in the container. You may even need to move a component out of the container, then back in. Check the Structure window to make sure each component nests properly. Each component inside a container should be indented in the Tree under its container.

20.6.3 Saving Before Experimenting

When designing in JDeveloper, expect to work by trial and error, especially when changing the layouts. Be sure to save your work before experimenting with a layout change.

You may discover that a particular layout you planned to use doesn't work as you expected. You may need to reexamine your design process and use a different configuration of containers, components, and layouts. For this reason, you may want to copy the container file (for example Frame1.java) to a different name and safe location at critical points so that, when you need to back up in your work, you don't need to start over completely.

20.6.4 Selecting a Final Layout Manager

If you've used the null or XYLayout Manager to design your Java program, you'll need to change the layout manager to one of the standard layout managers that is supported across different platforms.

To change the layout manager, see Section 20.8.3, "How to Change the Layout for a Container".

20.7 Working with Containers and Components

JDeveloper provides easy tools to help you generate your containers. Containers hold and manage other components. When you lay out a form to design the UI in JDeveloper you use containers. There are two general classes of containers:

  • Heavyweight Swing containers, extends their AWT equivalents and are thus heavyweight implementations, and include JFrame, JDialog, and JApplet.

  • Lightweight Swing containers, which don't contain operating system-specific code, and include, for example, JTabbedPane, JPanel, JSplitPane, and JScrollPane.

Containers are also components; you interact with them by getting and setting their properties, calling their methods, and responding to their events as with any other component.

20.7.1 Using Windows

A Window is a stand-alone top-level container component with no borders, title bar, or menu bar. Although a Window could be used to implement a popup window, you normally use a subclass of Window in your UI such as one of those listed in Table 20-7.

Table 20-7 Windows Subclasses

Window Description

Frame

A top-level window with a border and a title. A Frame has standard window controls such as a control menu, buttons to minimize and maximize the window, and controls for resizing the window. It can also contain a menu bar.

Dialog box

A popup window, similar to a Frame, but it needs a parent. Dialog boxes are used for getting input from the user or to present warning messages. It can also contain a menu bar. Dialog boxes are usually intended to be transient, or temporary, and can be one of the following types:

  • Modal: Prevents user input to any other windows in the application until that dialog box is dismissed.

  • Modeless: Lets the user enter information in both the dialog box and the application.


20.7.2 Using Panels

A Panel is a simple UI container, without border or caption, used to group other components, like buttons, checkboxes, and text fields. Panels are embedded within some other UI, such as in a frame or dialog. They can also be nested within other panels.

Table 20-8 Panels

Panel Description

Applet

A subclass of Panel used to build a program intended to be embedded in an HTML page and run in an Internet browser or applet viewer. Since Applet is a subclass of Panel, it can contain components, but does not have a border or caption.


20.7.3 Using Lightweight Swing Containers

The lightweight Swing containers available from JDeveloper's Component Palette pages include JMenuBar, JPopupMenu, JSplitPane, JScrollPane, JTabbedPane, and JToolbar. All are a subclass of JComponent. You can add other containers and components to these containers, combining components and their containers in various ways to get the interface you want.

Table 20-9 Lightweight Swing Containers

Lightweight Container Description

Menu Bar

The lightweight Swing containers available from the Component Palette pages include JMenuBar, JPopupMenu, JSplitPane, JScrollPane, JTabbedPane, and JToolbar. All are a subclass of JComponent. You can add other containers and components to these containers, combining components and their containers in various ways to get the interface you want.

Popup Menu

A small window which pops up and displays a series of choices, which you create in JDeveloper using the Menu Editor. A JPopupMenu is used for the menu that appears when the user selects an item on the menu bar. It is also used for "pull-right" menu that appears when the selects a menu item that activates it. Finally, a JPopupMenu can also be used anywhere else you want a menu to appear -- for example, when the user right-clicks in a specified area.

Split Pane

Manages two panes that are separated horizontally or vertically by a divider that can be repositioned by the user. You can choose which pane to add a component to. You can specify the components with the properties leftComponent and rightComponent, or topComponent and bottomComponent. In these properties, "Left" is equivalent to "Top" and "Right" is equivalent to "Bottom" -- so if you change the arrangement, your existing code still works. Subsequent adds to the same pane replace its contents with the new object.

Scroll Pane

Manages two panes that are separated horizontally or vertically by a divider that can be repositioned by the user. You can choose which pane to add a component to. You can specify the components with the properties leftComponent and rightComponent, or topComponent and bottomComponent. In these properties, "Left" is equivalent to "Top" and "Right" is equivalent to "Bottom" -- so if you change the arrangement, your existing code still works. Subsequent adds to the same pane replace its contents with the new object.

Along with its scroll bars and viewport, a JScrollPane can have a column header and a row header. Each of these is a JViewport object that you specify with rowHeader and columnHeader properties. The column header viewport automatically scrolls left and right, tracking the left-right scrolling of the main viewport. (It never scrolls vertically, however.) The row header acts in a similar fashion.

Tabbed Pane

Manages multiple panels that completely overlap each other. The user can select a panel to view by clicking on a "tab" attached to the panel (like the tab on a file folder). You add tabs in JDeveloper by dropping a JPanel onto the tabbed pane from the Component Palette. The tabPlacement property lets you position tabs on the top, bottom, left side, or right side of the container.

Toolbar

Provides a component which is useful for displaying commonly used Actions or controls. It can be dragged out into a separate window by the user (unless the floatable property is set to false). In order for drag-out to work correctly, it is recommended that you add JToolBar instances to one of the four 'sides' of a container whose layout manager is a BorderLayout, and do not add children to any of the other four 'sides'.


20.7.4 Understanding Component Properties in the Property Inspector

A property is a named attribute of a class that can affect its appearance or its behavior. A property can be:

  • Readable: These properties have a "get" method, which enables you to read the property's value. If it is a Boolean property, it can also use "is" to read the value.

  • Writable: These properties have a "set" method, which enables the property's value to be changed.

  • Both readable and writable: These properties have both "get" and "set" methods.

20.7.5 Setting Property Values in the Property Inspector

Properties are attributes that define how a component appears and responds at runtime. In JDeveloper, you set a component's initial properties during design time, and your code can change those properties at runtime.

The Property Inspector window displays the properties of the selected component(s) and is where you set the property values at design time for any component in your design. By setting properties at design time, you are defining the initial state of a component when the UI is instantiated at runtime.

Note:

To modify the initial property values at runtime, you can put code in the body of the methods or event handlers which you can create on the Events section of the Property Inspector.

20.7.6 Setting Shared Properties for Multiple Components

When you open the Property Inspector with more than one component selected in the Java Visual Editor, by default the Property Inspector displays all the common properties of the selected components.

Despite the fact that you may have selected multiple components in the Java Visual Editor, the Property Inspector still only displays property values for one component at a time. When the properties are shared among the selected components, sometimes the values will be the same, and in other cases, the property values may differ among the components. The Property Inspector helps you to identify which shared properties have differing values by representing the value in italics.

When the values for shared properties differ among the selected components, the property value that is displayed always belongs to the anchor selection. The anchor selection is the one that appears with hollow selection handles in the Java Visual Editor. You may alter the anchor selection by holding down the Shift key and clicking one of the other currently selected components. Altering the anchor selection changes which components' properties are shown in the Inspector, as well as altering which component the Java Visual Editor context menu operations apply to (for example, the Align context menu item).

When you change any of the shared properties in the Property Inspector, the property value changes to the new value in all the selected components.

20.7.7 Laying Out Your User Interface

This section explains the fundamental tasks you perform as you work with components and JDeveloper's UI design tools to create a user interface. If you're comfortable using controls in a graphical user interface environment, much of the material discussed here, such as selecting, sizing, and deleting components might be familiar to you.

Before you begin actually creating your UI, you may want to prototype your UI. For more information, see Section 20.6, "Prototyping Your UI with Layout Properties".

To design a user interface in JDeveloper:

To start your project:

These instructions assume that you have already created a project that includes a designable container class. If not, you will need to:

  1. Create or open a JDeveloper Project.

  2. Create an applet or an application.

20.7.8 How to Create a Frame

A frame is a top-level window with a border and a title. It has standard window controls such as a control menu, buttons to minimize and maximize the window, and controls for resizing the window.

The New Frame dialog adds a new class to the active project. It adds necessary import statements, creates a default constructor, and it creates a jbInit() method in which JDeveloper sets properties and other initialization code used by the Java Visual Editor.

To add a frame:

  1. Open or create a project.

  2. Choose File > New to locate the New Frame dialog in the New Gallery.

  3. In the Categories list, expand Client Tier and select Swing/AWT.

  4. In the Items list, select Frame and click OK to launch the New Frame dialog.

  5. In the New Frame dialog, enter the name of the package and class.

  6. Choose which frame type to extend.

  7. Type the frame title.

  8. If there are any options (such as Menu Bar) select any you feel are appropriate.

  9. Click OK to create the frame and its source code.

    The frame is displayed as a.java source file in the Navigator.

To view the frame in JDeveloper:

  • Right-click the file in the Navigator and choose Open and click the Design tab to use the interactive UI design tools, such as the Component Palette and the Property Inspector.

  • Click the Source tab begin editing the source code directly.

20.7.9 How to Create a Panel

A panel is a UI container that groups components such as buttons, checkboxes, and text fields. A panel has a border and may have a title if the border selected is a TitledBorder. Typically, a panel is embedded within a dialog box or frame.

The New Panel dialog adds a new class to the opened project that extends a panel you select. It creates a default constructor, and a jbInit() method in which JDeveloper puts property setters and other initialization code used by the Java Visual Editor.

To create a panel:

  1. Open or create a project.

  2. Choose File > New to locate the New Panel dialog in the New Gallery.

  3. In the Categories list, expand Client Tier and select Swing/AWT.

  4. In the Items list, select Panel and click OK to launch the New Panel dialog.

  5. In the New Panel dialog, enter a name of the panel's class and package.

  6. Choose the base class from which the panel is derived.

    You can choose from any of the base classes installed with JDeveloper. If you prefer, you can search for another class that isn't from an installed package using the browse button. By default, the selection is limited to the panel container provided with the core J2SE (Java 2, Standard Edition) and Swing classes.

  7. Click OK to create the panel and its source code.

    The panel is displayed as a.java source file in the Navigator.

To view the panel in JDeveloper:

  1. Right-click the file in the Navigator and choose Open and click the Design tab to use the interactive UI design tools, such as the Component Palette and the Property Inspector.

  2. Click the Source tab begin editing the source code directly.

20.7.10 How to Create a Dialog Box

A dialog box is a popup window with a border and a title. Dialog boxes are typically used to collect user input.

The New Dialog dialog creates a new class that extends Dialog or JDialog and adds it to the current project. It adds the necessary import statement. It also creates a jbInit() method in which JDeveloper puts property setters and other initialization code used by the Java Visual Editor. The jbInit() method will be invoked when using any of the constructors.

After adding the dialog box, you can design the dialog directly using the Java Visual Editor. This is how you add buttons and other controls to your new dialog box.

To create a dialog box:

  1. Open or create a project.

  2. Choose File > New to locate the New Panel dialog in the New Gallery.

  3. In the Categories list, expand Client Tier and select Swing/AWT.

  4. In the Items list, select Dialog and click OK to launch the New Dialog dialog.

  5. In the New Dialog dialog, enter the name of the dialog box's package and class. The file name is automatically filled in for you; it is assigned the same name as the class and is saved to the package directory.

  6. Choose whether to extend java.awt.Dialog or javax.swing.JDialog.

  7. Click OK to create the dialog box and its source code.

    The dialog box is displayed as a.java source file in the Navigation window.

To view the dialog box in JDeveloper:

  • Right-click the file in the Navigator and choose Open and click the Design tab to use the interactive UI design tools, such as the Component Palette and the Property Inspector.

  • Click the Source tab begin editing the source code directly

20.7.11 How to Use a Dialog Box That is Not a Bean

Once the dialog box has been created and its UI designed, you will want to test or use your dialog box from some UI in your program.

To test or use your dialog box:

  1. Instantiate your dialog class from someplace in your code where you have access to a Frame which can serve as the parent Frame parameter in the dialog constructor. A typical example of this would be a Frame whose UI you are designing, which contains a Button or a MenuItem which is intended to bring up the dialog box. In applets, you can get the Frame by calling getParent() on the applet.

    For a modeless dialog box (which we are calling dialog1 in this example), you can use the form of the constructor that takes a single parameter (the parent Frame) as follows:

    Dialog1 dialog1=new Dialog1(this);

    For a modal dialog box, you will need to use a form of the constructor that has the boolean modal parameter set to true, such as in the following example:

    Dialog1 dialog1=new Dialog1(this, true);

    You can either place this line as an instance variable at the top of the class (in which case the dialog box will be instantiated during the construction of your Frame and be reusable), or you can place this line of code in the actionPerformed event handler for the button that invokes the dialog box (in which case a new instance of the dialog box will be instantiated each time the button is pressed.) Either way, this line instantiates the dialog box, but does not make it visible yet.

    (In the case where the dialog is a bean, you must set its frame property to the parent frame before calling show(), rather than supplying the frame to the constructor.)

  2. Before making the instantiated dialog box visible, you should set up any default values that the dialog box fields should display. If you are planning to make your dialog into a Bean, you need to make these dialog box fields accessible as properties. You do this by defining getter and setter methods in your dialog class.

  3. Next, you have to cause the dialog box to become visible during the actionPerformed event by entering a line of code inside the event handler that looks like this:

    dialog1.show();

  4. When the user presses the OK button (or the Apply button on a modeless dialog box), the code that is using the dialog box will need to call the dialog's property getters to read the user-entered information out of the dialog, then do something with that information.

    • For a modal dialog box, you can do this right after the show() method call, because show() doesn't return until the modal dialog box is dismissed. You can use a result property to determine whether the OK or Cancel button was pressed.

    • For a modeless dialog box, show() returns immediately. Because of this, the dialog class itself will need to expose events for each of the button presses. When using the dialog box, you will need to register listeners to the dialog's events, and place code in the event handling methods to use property getters to get the information out of the dialog box.

20.7.12 How to Create a Tabbed Pane

A tabbed pane is a UI container that groups components such as buttons, checkboxes, and text fields on multiple panels. Each panel has a title and a tab that the end user clicks to view the panel contents.

To create a tabbed pane:

  1. Create a frame or other container. For more information, see Section 20.7.8, "How to Create a Frame."

  2. In the Swing Containers page of the Component Palette, click the JTabbedPane component.

  3. Click inside the container in the Java Visual Editor to drop the tabbed pane with its default size.

  4. Resize the tabbed pane as desired.

  5. To add the first tab to the tabbed pane, click the JPanel component in the Swing Containers page of the Component Palette, then click on the JTabbedPane inside the Java Visual Editor.

  6. To add additional tabs to the tabbed pane, after you click the JPanel component in the Component Palette, you must click specifically on the tab itself of a previously added tab panel.

  7. To add a layout panel (one that has no tabs) to any of the tabbed pane tabs, click the JPanel component in the Swing Containers page of the Component Palette, then click the content area of the JTabbedPane inside the Java Visual Editor (in this case, do not click the tab itself).

    To work with a panel that is not currently the top most tab in the Java Visual Editor, click directly on the tab. When you select tab, you also raise the panel to the top of the stacking order. Alternatively, you can select tab panels by choosing the desired panel in the Structure Window. To view the panels you have added to the tabbed pane, expand the UI folder, expand the dataPanel node, and finally expand the JTabbedPane node to see the list of JPanels.

20.8 Working with Components in a Container

You can create and manage your container components using the JDeveloper tools.

20.8.1 How to Add Components to Your User Interface

There are several ways to insert a component from the JDeveloper Component Palette into a UI container you create.

  • Using the mouse to select, insert, and position a component

  • Using keyboard bindings to select and insert a component

When you visually add a component in the Java Visual Editor, JDeveloper generates an instance variable for the component and adds it to the source code. When you delete a component, the Java Visual Editor deletes the associated lines from the code.

To add a component to your UI using the mouse:

  1. Create a container component.

  2. Choose the desired component list from the Component Palette dropdown menu.

  3. Click the desired component in the palette.

  4. To insert the selected component into the container, do one of the following:

    • Click inside the container to insert the component at its default size, or

    • Drag the mouse in the Java Visual Editor to form a bounding box from the initial mouse click to a final point which represents the desired dimensions of the object to be created. Dragging to a specific size is only appropriate when layouts for a container that consider individual component dimensions. Ultimately, the layout manager for each container in your UI will determine its components' size and position, or

    • Drop the component onto the desired container in the Structure window. Be aware that this method gives you no control over where the component appears in the container.

To add a component to your container using only keystokes:

  1. Create a container component. For more information, see Section 20.8, "Working with Components in a Container."

  2. Choose the desired component list from the Component Palette dropdown menu.

  3. To select a component from the palette, press the tab key to focus on the desired component, then press the spacebar to select the component.

  4. To insert the selected component into the container, press Enter.

    The inserted component appears in the top, lefthand corner of the UI container. You may use the Property Inspector to size and position the inserted component.

To add multiple instances of a component:

Press the Shift key while clicking the component in the Component Palette. You may release the Shift key and the palette will still remain in multiple creation mode.

Click the arrow tool in the Component Palette to turn off multiple object creation.

20.8.2 How to Set Component Properties at Design Time

The Property Inspector window displays the properties of the component selections you make in the Java Visual Editor. Use the Property Inspector window to set the property values at design time for any component in your UI design.

To set a component's properties at design time:

  1. Select a component in the Java Visual Editor or in the Structure window.

  2. To display the Property Inspector with the values for the selected component, choose View, then Property Inspector or right-click the component in the Java Visual Editor and choose Property Inspector. The Property Inspector window is highlighted.

  3. To display the Property Inspector with the values for the selected component, choose View Property Inspector or right-click the component in the Java Visual Editor and choose Property Inspector. The Property Inspector window is highlighted. OR

    In the Property Inspector toolbar, type the name of the property in the Find text field, and press Enter to display the property in the Inspector. If you entered a partial name or more than one property exists by the same name, you can use the Up or Down arrow buttons to jump to properties matching the entered name.

  4. Enter the value in the right column one of the following ways:

    • When there is only a text field, you simply type the string value for that property, for example a text value or a number value, then press Enter.

    • When the value field is displayed with a down arrow, click the down arrow and choose a value from the list, then press Enter.

    • When the value field shows an ellipses (...) button, click it to display a property editor for that property, for example, a color or font selector. Set the values in the property editor, then press OK.

To set properties for multiple components:

  1. Hold down the Ctrl key or Shift key, and select the desired components.

  2. The Property Inspector displays the properties that are shared by selected components. Select and edit the desired property in the Property Inspector. Editing the value of a shared property will cause all selected components to have the same value. If the value is shown in italic font, that means the value belonging to the anchor component's value differs from the other selected components.

Note:

The Ctrl key causes the selection state of the selected object to be toggled (from either not selected to selected, else from selected to not selected). Using the Shift key to make selections also changes the object's anchor usage:
  • If the object is not yet selected, it will become selected and become the anchor.

  • If the object is already selected, it will just become the anchor.

Using either the Ctrl or Shift key, if a control goes from being not selected to selected, it will become the new anchor until the user changes the anchor using the Shift select action.

20.8.3 How to Change the Layout for a Container

JDeveloper provides a layout property in the Inspector, in which you can choose a new layout for any container in the Java Visual Editor.

To select a new layout:

  1. Select the container in the Structure window.

  2. Click the Properties tab in the Inspector, select the layout property, and click its value field.

  3. Click the down arrow in the layout property's value field and choose a layout from the dropdown list.

JDeveloper does the following:

  • Substitutes the new layout manager in the Structure window.

  • Changes the source code to add the new layout manager and updates the container's call to setLayout.

  • Changes the layout of components in the Java Visual Editor.

  • Updates the layout constraints for the container's components in the Inspector and in the source code.

20.8.4 How to Modify Component Layout Constraints

When you drop a component into a container, JDeveloper creates an appropriate constraint object or value for that container's layout manager. JDeveloper automatically inserts this constraint value or object into the constraint property of that component in the Property Inspector. It also adds it to the source code as a parameter of the add() method call in the jbInit() method.

To edit a component's layout constraints:

  1. Select the component in the Java Visual Editor or the Structure window.

  2. Select the constraints property in the Property Inspector and click its value field.

    When working with a null layout manager, there is no constraints property on the children, set the layout constraints on the bounds property instead.

  3. Use the Property Editor to modify the constraints, or

    Click the desired toolbar constraint button in the Java Visual Editor and, when available, choose the value from the dropdown list.

20.8.5 How to Select Components in Your User Interface

Before attempting to select an existing component in your UI, be sure the selection arrow in the Component Palette is depressed. Otherwise, you may accidentally place a component on your UI.

To select a single component, do one of the following:

  • Click the component in the Java Visual Editor.

  • With focus on the Java Visual Editor, tab to the component (Tab = forward; Shift+Tab = backward).

  • Select the component in the Structure window

To select multiple components, hold down the Ctrl key and do one of the following:

  • Click the components in the Java Visual Editor one at a time.

  • Click and drag around the outside of the components you want to select.

Note:

We recommend using the Ctrl key to perform multiple selections because the Shift key changes which of the selected objects is the 'anchor' of the selection. The selection anchor is the object whose property values will be displayed in the Property Inspector; it is also the object to which context menu actions apply (i.e., alignment).

As you drag, you surround the components with a rectangle, or "lasso." When this rectangle encloses all the components you want to select, release the mouse button. If necessary, you can then use Ctrl+click to individually add or remove components from the selected group.

Hold down the Ctrl key and select the components in the Structure window.

20.8.6 How to Size and Move Components

For many layouts, the layout manager determines the size of the components by constraints, making sizing in the Java Visual Editor have no effect. However, when working with null, XYLayout, or GridBagLayout, you can size components when you first place them in your UI, or you can resize and move components later.

Note:

GridBagLayout currently ignores size on creation, but you can then resize components after creation.

To size a component as you add it:

  1. Select the component in the Component Palette.

  2. Place the cursor where you want the component to appear in the UI.

  3. Drag the mouse pointer before releasing the mouse button. As you drag, an outline appears to indicate the size and position of the control.

  4. Release the mouse button when the outline is the size you want.

To move a component one pixel at a time:

  1. Make sure that the snap-to-grid feature is turned off (see Tools > Preferences, Java Visual Editor).

  2. Select the component in the Component Palette.

  3. Hold down the Ctrl + shift keys, then use the direction arrow keys to move the object one pixel at a time

To resize or move a selected component:

  1. Click the component in the Java Visual Editor or in the Structure window to select it.

    When you select a component, sizing handles or nibs appear on the perimeter of the component. For some containers, a move handle appears in the middle of the component.

  2. Click the appropriate outer handle and drag to resize.

  3. Click anywhere in the component and drag it any direction to move it. If the component is a container that is covered with other components, use the center move handle to drag it.

To resize or move a group of selected components:

  1. Do one of the following to select the group of components to be changed:

    • Hold down the Ctrl key and select each of the components.

    • Hold down the left mouse button and draw a "lasso" around the group of components you want to change.

    When you select a component, sizing handles or nibs appear on the perimeter of the component. For some containers, a move handle appears in the middle of the component.

  2. Click the appropriate outer handle and drag to resize.

  3. Click anywhere in the component and drag it any direction to move it. If the component is a container that is covered with other components, use the center move handle to drag it.

  4. Right-click and choose Size and Space, then choose the desired operation.

    OR

    Click the desired size button in the Java Visual Editor toolbar. Operations which are invalid for the currently selected components appear disabled in the toolbar and context menu.

20.8.7 How to Group Components

JDeveloper provides a number of container components for grouping components together so they behave as a single component at design time.

For instance, you might group a row of buttons in a Panel to create a toolbar. Or you could use a container component to create a customized backdrop, status bar, or checkbox group.

When you place components within containers, you create a relationship between the container and the components it contains. Design time operations you perform on the containers, such as moving, copying, or deleting, also affect any components grouped within them.

To group components by placing them into a container:

  1. Add a container to the UI.

    If you are working in a layout that considers size such as the GridBagLayout, null layout or XYLayout, you can drag to size it.

  2. Add each component to the container, making sure the mouse pointer falls within the container's boundaries. (The status bar at the bottom of JDeveloper displays which container your mouse is over.) You can add a new component from the Component Palette, or drag an existing component into the new container.

    As you add components, they appear inside the selected container in the Java Visual Editor, and under that container in the Structure window.

Tip:

If you want the components to stay where you put them, change the container's layout to null before adding any components. Otherwise, the size and position of the components will change according to the layout manager used by the container. You can change to a final layout after you finish adding the components.

20.8.8 How to Change Component Z-Order

JDeveloper lets you modify the order in which components, which have been visually stacked one on top of another, appear in the UI design. The topmost component specified by Z-order is the one which the user sees at runtime by default.

Note:

Although the Java Visual Editor only displays the topmost component in a stack, you can view the Z-order of the stack in the Structure window: the topmost component appears first in the list of nodes, followed by the next component in the stack, and so on. When you change the Z-order, the Structure window is updated to display the new order.

To change the Z-order of the topmost component:

  1. Select the component in the Java Visual Editor from that is currently on top of the stack.

  2. Right-click and choose Order > Send to Back.

To change the Z-order of a component that is not visually on top:

  1. Select the stacked component in the Structure window for which you want to change the order.

  2. In the Java Visual Editor, right-click and choose Order, then choose either Bring to Front or Send to Back.

20.8.9 How to Cut, Copy, Paste and Delete Components

JDeveloper supports Cut, Copy, Paste and Delete functionality in the Java Visual Editor. You can perform these operations between files of the same project or different projects.

Note:

When you cut, copy, paste from one file to a file in another project, you may be required to update your project properties on the target project to include additional libraries. If the target project does not define the right libraries for the pasted object, the paste will fail since the Java Visual Editor will not recognize the class of the incoming objects.

20.8.10 How to Copy a Component

Visual components copied in the Java Visual Editor are not copied to the system clipboard, and cannot be transferred into other applications. Use a screen capture utility to create an image of a control, or copy the source text to use the Java code in another Java development environment.

When you copy a component that has defined event methods, the event listener is copied with the component, but not the event handler. This is because in most cases it's the format of the control, and not the behavior, that you want to copy. If your goal is to copy the control and its behavior to a different Java class file, you need to separately copy the handler: open the file in the Code Editor, locate the handler code, select it, and choose Edit > Copy.

To copy one or more components:

  1. Select the components you want to copy. For more information, see Section 20.8.5, "How to Select Components in Your User Interface."

  2. Choose Edit > Copy.

The components are copied to a local clipboard in JDeveloper.

20.8.11 How to Cut a Component

Before you cut your component be sure to paste the previously cut object since cutting the event code will overwrite the contents of the clipboard.

To cut a component from your user interface:

  1. Select the components you want to cut.

  2. Choose Edit > Cut.

The component is removed from the Java Visual Editor and placed into a local clipboard only accessible by JDeveloper (not to the system clipboard). If you quit JDeveloper without pasting the control into a container, the cut version of the control will be lost.

The cut command is the first step in a cut and paste action. If you just want to remove a component, see Deleting a component, below. Deleting a component removes it without changing the contents of your clipboard. If you get in the habit of using the cut command to remove items permanently, there is a chance that one day you will inadvertently replace something in the clipboard that you would rather have kept.

When you cut a component that has defined event methods, the event listener is cut with the component. The event handler is not removed from the source code, nor is it placed on the clipboard. There are two reasons for this:

  • In most cases, it isn't the behavior of the control, but the format that you want to retain.

  • More than one component may use the same event handler, so removing it from the code may impact other parts of your program.

To cut an event handler in the Code Editor, locate the handler code, select it, and choose Edit, then Cut.

20.8.12 How to Paste a Component

The components you copy or cut from a JDeveloper Design window can be pasted into any other designable class file.

To paste a component:

  1. Open the file to which you want to paste the component in the Java Visual Editor.

  2. Select the container to which you want to paste the component.

  3. Choose Edit, then Paste.

The JavaBeans components you paste will add any existing event listener code from the original component to your source code. The event handler code does not get copied or cut with the component: if you want to use the same event handler, you need to copy and paste the handler separately using the Code Editor.

20.8.13 How to Delete a Component from your UI

Delete a component when you want to remove it from your Java program without affecting the contents of the clipboard.

To delete a component:

  1. Select the component in the Java Visual Editor or the Structure window.

  2. Press the Delete key.

When you delete a JavaBeans component from the Java Visual Editor, the event listener methods, if any, are deleted from the source code, but the event handler methods are not. If you want to remove the event handler methods, you need to delete them in the Code Editor.

20.9 Working with Menus

The basic parts of a menu are referred to using the following terms:

  • A menu bar is displayed at the top of a frame. It is composed of one or more top-level menus, such as File, Edit, or Help. A JMenuBar may have any component as a child, such as a JComboBox or JToggleButton, for example.

  • A menu is a child of menu bar and contains a collection of menu items, submenus, and separators.

  • A submenu is a menu whose parent is another menu instead of the menu bar.

  • A menu item is an individual element on a menu which can invoke a command. Menu items can have attributes such as being disabled (gray) when not allowed, or checkable so their selection state can be toggled.

  • An accelerator, also known as an keyboard shortcut, allows an alternative way to invoke a menu item. When a menu item has an accelerator, it is displayed at the right of the menu item.

  • The separator bar helps to visually group related items. It does not invoke a command.

20.9.1 Understanding Menu Components

There are four types of menu component on the Component Palette: a MenuBar, JMenuBar, PopupMenu, and JPopupMenu.

  • A MenuBar or a JMenuBar is attached to the main UI Frame, and appears at the top of the frame.

  • A PopupMenu or a JPopupMenu appears when the user right-clicks in your UI. At runtime, popup menus do not appear on the menu bar, instead they are displayed where the user invokes them.

All of these controls can be edited in the Property Inspector.

The first MenuBar or JMenuBar control dropped onto the UI container is considered the current menubar for your UI. However, you can create more than one menubar for an application; they are displayed in the Inspector in the frame's MenuBar property. Select a menu from the MenuBar property dropdown list to make it active.

Note:

Menu components are only editable at design time in the Menu Editor, not the Java Visual Editor. The menu bar and its top-level menus display in the Java Visual Editor, but they are not selectable and cannot be edited from there. However, you can always see and select them in the Structure window. To see how the menu looks in your UI, run your application.

20.9.2 Using the Menu Editor

You access the Menu Editor by opening the Java file in the Java Visual Editor, which makes the Structure window visible. Then, in the Structure window, when you click on a menu, menu item, or menu root node, the Menu Editor appears.

There are multiple ways that you work with the Menu Editor to create menus:

  • Keyboard Arrow, Esc, and Enter keys let you change the focus of the editable menu component

  • Drag and drop operations let you move menus or menu items

  • Menu Editor toolbar or menu item context menus let you insert menu components

For instance, you can type labels directly into the menu component which has the current focus in the Menu Editor as indicated by the highlighted box. Pressing Enter validates the label and lets you type the next menu component label. You can also use the keyboard arrow keys to move the current focus in the Menu Editor to another position in the menu you want to edit. The Esc key changes the focus from anywhere inside a menu to the menu bar.

In addition to labels that you specify, you can insert various menu components either through the Menu Editor toolbar or the commands duplicated by right-clicking on a menu component. These operations are supported by the toolbar and context menu:

  • Insert MenuItem

  • Insert Separator

  • Insert Submenu

  • Enable (or disable) menu item

  • Make menu item checkable

Additionally, you can rearrange entire menus or single menu items using drag and drop operations by clicking along the menus in the menu bar or inside the menus in their menu items.

20.9.3 Interacting with the Code Editor and the Property Inspector

JDeveloper synchronizes your changes as you work. As you edit menu items in the Menu Editor, all changes are reflected in the source code by the Code Editor and the Property Inspector. When you make changes to the menus in the source code or the Property Inspector, those changes are reflected in the Menu Editor.

For example, when you add a Menu to a MenuBar component, this Menu appears in the Structure window as a child of the MenuBar. Also, when you change properties for Menu or MenuItem (like text or enabled), those changes are reflected in the code, Menu Editor, and Property Inspector.

Since JDeveloper also maintains synchronization with the Code Editor, there is no need to save your menu design manually. JDeveloper generates the code which you can view and edit in the Code Editor as you use the Menu Editor. The generated code is saved when you save your Java source file. The next time you open the Java file and select a MenuBar component in the Structure window, the Menu Editor will open and reload everything for that component.

Once you add a menu component to the UI design, you can use the Menu Editor to design the menu structure. To activate the menus in the user interface, you must use the Property Inspector to attach the menu items to events, or enter the code manually in the Code Editor.

20.9.4 How to Add a Menu Component to a Frame

Since a non-popup menu can only be attached to container, such as a JFrame or a JDialog, you must first open or a container file. You can open one in one of the following ways:

To add a menu component to the UI:

  1. Right-click the UI frame file in the Navigator and choose Open.

  2. Select your main UI frame in the Java Visual Editor or in the Structure window.

  3. Click a menu component on the Component Palette and drop it anywhere in the Java Visual Editor.

    You can choose either a menu bar or a popup menu.

    • A menu bar is attached to the main UI frame or dialog, and is displayed at the top of the application.

    • A popup menu is displayed when the user right-clicks in your UI. Popup menus do not have menu bars.

    Alternatively, you can open a file that already contains a menu component.

    At this point, nothing is visible on the UI. The added menu component is displayed in the Structure window and opens in the Menu Editor.

20.9.5 How to Add a Popup Menu

Popup menus can be created so they open on a particular UI container. You add the popup menu to the container and create an event handler to specify the user's action that triggers the popup.

To add a popup menu:

  1. Open your UI class in the Java Visual Editor.

  2. Drop a popup menu from the AWT or Swing Containers Component Palette into the Structure window. The Menu Editor appears.

  3. Add one or more menu items to the popup menu. For more information, see Section 20.9.8, "How to Add a Menu Item".

  4. Expand the UI folder in the Structure window and select the panel or other component whose event you want the popup menu attached to so you can see that component in the Property Inspector. For the following example, panel1 was selected.

  5. In the Property Inspector, click the Events tab and click the desired event value field.

  6. Type the stub name of the event into the event value field and press Enter to create an event-handling method stub in the source code with the supplied name. For the following example, the MouseClicked event was selected and the name panel1_mouseClicked entered.

  7. Edit your event-handler stub to resemble the following:

    Example 20-2 Event Handler Stub

    void panel1_mouseClicked(java.awt.event.MouseEvent e) { 
      panel1.add(popupMenu1); 
       if (e.isPopupTrigger()) {   
        // Make the PopupMenu visible relative to the current mouse  
        // position in the container.  
       opupMenu1.show(panel1, e.getX(), e.getY());
       }
    }
    
  8. Add event handlers to the popup menu's menu items as needed for your application.

20.9.6 How to Create a Submenu

Submenus can appear on menus to provide additional, related commands. Such nested lists are displayed with the menu text followed by an arrow. JDeveloper supports as many levels of submenus as you want to build into your menu.

Organizing your menu structure with submenus can save vertical screen space. However, for optimal design purposes you probably want to use no more than two or three menu levels in your UI design.

When you move a menu off the menu bar into another menu, it becomes a submenu. Similarly, if you move a menu into an existing submenu, it forms another submenu under the submenu.

To create a submenu:

  1. Select the menu item to which you want to add a submenu.

  2. Right-click and choose Insert Submenu.

    Alternatively, you can create a submenu by selecting the menu item and pressing Ctrl and the right arrow key.

  3. Click the new submenu item and type a name for the nested menu item, or drag an existing menu item into this placeholder.

  4. Press Enter, or the Down arrow, to create the next placeholder.

  5. Repeat steps 3 and 4 for each item you want to create in the submenu.

  6. Press Esc to return to the previous menu level.

20.9.7 Customizing Menus with the Menu Editor

Use the JDeveloper Menu Editor to customize and manage your menu items.

20.9.8 How to Add a Menu Item

When you first open the Menu Editor, it displays the menu bar or popup menu that you opened with any defined menu items. There is also a blank menu to the right of the last menu in the menubar and a placeholder at the end of each menu, indicated by a dotted rectangle.

To add menu items to an existing menu:

  1. In the Menu Editor, select the position on the menu bar where you want to add a new menu, or on the menu select where you want to add a new menu item, separator or submenu.

  2. Right-click and choose Insert MenuItem.

  3. While the menu item appears highlighted in the Menu Editor, type the text for the new menu component's label.

    As you start to type, the highlighted dotted rectangle changes to a normal text edit field containing a cursor. The text field will scroll as you type to accommodate labels longer than the edit field.

  4. When you're finished typing, press Enter.

    The width of the list expands if necessary to display all the labels in the list, and a placeholder for the next menu item is automatically selected.

  5. Enter a label for each new item you want to create in the list, or press Esc to return to the menu bar.

    In addition to directly selecting items in the Menu Editor, you can use the arrow keys to move from the menu bar into a menu, and to move between items in the list; press Enter to complete an action.

20.9.9 How to Disable a Menu Item

You can prevent users from accessing certain menu commands based on current program conditions without removing the command from the menu. For example, if no text is currently selected in a document, the Cut, Copy, and Delete items on the Edit menu are disabled and are displayed dimmed.

Use the enabled property to disable a menu item. As with most properties, you can specify an initial value for enabled using the Inspector. The default enabled state of a menu item is True; this may change when an event occurs.

To disable a menu item:

  1. Select the menu item in the Menu Editor or in the Structure window.

  2. Right-click and choose Enabled.

  3. Alternatively, in the Property Inspector, set the enabled property for the menu item to false.

    In contrast to the visible property, the enabled property leaves the item visible. A value of false dims the menu item.

20.9.10 How to Specify Accelerators

Accelerators enable the user to perform an action without accessing the menu directly by typing in an accelerator key combination. For example, a commonly used accelerator for File > Save is Ctrl+S.

To specify an accelerator for a menu item:

  1. Select the menu item in the Design view, or in the Structure window.

  2. In the Property Inspector window, select the accelerator property from the Model section, and choose KeyStroke from the dropdown menu. Use the accelerator dialog to supply the key combination.

20.9.11 How to Insert a Separator Bar

A separator bar inserts a line between menu items and between sibling menu components, including menu items and submenus. You can use separator bars to indicate groupings within the menus.

To insert a separator bar on a menu:

  1. Select the menu item before which you want a separator, or choose the blank item at the end of a menu.

  2. Right-click and choose Insert Separator.

    The separator bar is inserted above the selected menu item.

  3. Alternatively, you can type a hyphen (-) for the menu item label.

    Using the right-click menu to insert the separator will result in the line addSeparator() to be generated, whereas using the hyphen for the label will use the more memory intensive creation of an additional class member whose label is a hyphen.

20.9.12 How to Create Checkable Menu Items

To make a menu item checkable, you need to change the menu item from a regular MenuItem component to a CheckboxMenuItem. A CheckboxMenuItem has a State property (boolean) that allows an event-handler to determine how the associated event, or behavior, should be executed.

  • The state property for a checked menu item is set to true.

  • The state property for an unchecked menu item is set to false.

To change a regular menu item to a CheckboxMenuItem:

  1. Select the menu item.

  2. Right-click and choose Checkable.

20.9.13 How to Insert and Delete Menus and Menu Items

To insert a new, blank menu or menu item, place the cursor on an existing menu item and right-click and choose Insert (Menu or Menu Item).

Menus are inserted to the left of the selected item on the menu bar, and menu items are inserted above the selected item in the menu.

To delete a menu item, select the menu item and press the Delete key.

Note:

A default placeholder (which you cannot delete) appears after the last menu on the menu bar and below the last item on a menu. This placeholder does not appear in your menu at runtime.

20.9.14 How to Move a Menu Item

In the Menu Editor, you can move menus and menu items by dragging and dropping them. When you move a menu item with submenu items, the submenu items move as well.

You can move menu items and submenu items:

  • Within a menu

  • To other menus

You move entire menus along the menu bar.

To move a menu item:

  1. Click and drag the menu item or submenu item to the new location.

    If you are dragging the menu item to another menu, drag it along the menu bar until the cursor points to the new menu.This action causes the menu to open, enabling you to drag the item to its new location.

  2. Drop the menu item or submenu item at the new location.

To move a menu:

  1. Click menu label in the menu bar and drag to the new location across the menu bar until the cursor points to the location where you want the menu to appear.

  2. Drop the menu at the new location.

20.10 Working with Event Handling

Use UI design tools in JDeveloper to attach event handler code to component and menu events.

In building your Java program, you can think of your code as being divided into two categories: initialization code and event-handling code.

  • Initialization code is executed when the UI components are created. You can think of this primarily as "start up" code for the components. This initialization code includes anything in the jbInit() method that all JDeveloper-designed GUI classes have. JDeveloper generates this code based on your UI design. For example, JDeveloper generates a button1.setLabel("OK") method call because you set the label property of a button, using the Inspector, to "OK".

  • Event-handling code is the code that is executed when the user performs an action, such as pressing a button or using a menu item. JDeveloper creates the stub (empty) event-handling method for you when you enter an event name in the Inspector for that component and press Enter. In that stub, you write code to handle the actual action caused by the event.

Your entire program consists of the initialization code, which says how things should look when they first appear, and the event-handling code, which says what should happen in response to user input.

There are some JDeveloper components, such as dialogs, which normally appear only when event-handling code is executed. For example, a dialog isn't part of the UI surface you are designing in the Java Visual Editor; instead it is a separate piece of UI which appears transiently as a result of a user selecting a menu item or pressing a button. Therefore, some of the code associated with using the dialog, such as a call to its show() method, might be placed into an event-handling method.

20.10.1 How to Attach Event Handling Code to Menu Events

In Swing, a menu item has actionPerformed events and CheckboxMenuItems have itemStateChanged events. Code that you add to the actionPerformed event for a menu item is executed whenever the user chooses that menu item or uses its accelerator keys.

To add code to a menu item's event:

  1. Open the Java Visual Editor for your UI frame.

  2. Add a menubar to your UI frame and insert menus and menu items into the menubar. Alternatively, you can open a file that already contains a menu.

  3. Select a menu item in the Menu Editor or the Structure window.

  4. In the Property Inspector, click the Events tab and click the desired event value field.

  5. Type the stub name of the event into the event value field and press Enter to create an event-handling method stub in the source code with the supplied name.

    When you enter a name in the event value field, JDeveloper open the Code Editor and displays the source code in the Structure window. The cursor is positioned in the body of the newly created event-handling method, ready for you to enter code.

  6. Inside the open and close braces, enter the code you want to have executed when the user clicks this Menu command.

20.10.2 How to Attach Event-Handling Code to a Component Event

Using the Events page of the Inspector, you can attach handlers to component events and delete existing event handlers.

To attach event-handling code to a component event:

  1. Select the component in the Java Visual Editor or in the Structure window.

  2. In the Property Inspector, select the Events tab to display the Events for that component and click the desired event value field.

  3. Type the stub name of the event into the event value field and press Enter to create an event-handling method stub in the source code with the supplied name.

    JDeveloper creates an event handler with the new name and switches to that event handler in the source code. JDeveloper also inserts some additional code into your class, called an Adapter, to make the connection from the event to your event handling method.

  4. Inside the stub of the event handler write the code that specifies the response to that component event.

    Note:

    To find out what methods and events a component supports, right-click that component in the Code Editor and choose Go to Declaration to open the class in the Code Editor. You can also right-click the component and choose Browse Javadoc to view the documentation for that class.

To quickly create an event handler for a component's default event:

  1. Select a component on the Component Palette and add it to your UI.

  2. Double-click the component in the Java Visual Editor. An event stub is created and focus switches to that event handler in the source code.

  3. Add the necessary code to the event handler to complete it.

Note:

The default event is defined by beanInfo, or as actionPerformed if none was specified.

20.11 Working with Applets

Use JDeveloper's UI design tools to create an applet class and applet HTML file. You can also convert any HTML files that contain applets to a format that can be used with the Java Plug-in.

20.11.1 How to Create an Applet

In JDeveloper, you can easily create a skeleton Java applet and then edit it with the Code Editor.

To create a Java applet:

  1. In the Navigator, select the project in which you want to create the new applet.

  2. Choose File > New to open the New Gallery.

  3. In the Categories tree, expand Web Tier and select Applet.

  4. In the Items list, double-click Applet to open the Create Applet dialog.

    This will open the Create Applet dialog that will create the applet for you based on information you specify, including the name, package and class it extends.

When you are finished, you will have a skeleton.java file containing the applet class, based on the details you entered. You can edit this file in the Code Editor. Using JDeveloper you will also be able to embed your applet within an HTML page, which you can create with the Applet HTML File wizard. You can also run the applet standalone in order to test it from JDeveloper.

20.11.2 How to Create an Applet HTML File

In JDeveloper, you can easily create a Java applet HTML file that acts as a container for your applet.

To create a Java applet HTML file:

  1. In the Navigator, select the project that contains your applet.

  2. Choose File > New to open the New Gallery.

  3. In the Categories tree, expand Client Tier and select Swing/AWT.

  4. In the Items list, double-click Applet HTML Page to open the Applet HTML File wizard.

The Applet HTML File wizard will create the file for you based on information you specify, including the file location, code attributes, positioning attributes, and applet parameters. You can also create an optional deployment profile.

20.11.3 How to Convert an HTML Page that Contains an Applet

JDeveloper includes the Java Plug-in HTML Converter; it can convert any HTML files that contain applets to a format that can be used with the Java Plug-in.

To convert HTML files that contain applets:

  1. Choose Tools > Convert HTML to open the Java Plug-in HTML Converter.

  2. Specify a file or the directory path of the files to be converted.

  3. Specify matching file names if you entered a directory path, and optionally select Include Subfolders.

  4. Change or accept the default folder for backup files.

  5. Select the template file to use from the dropdown list.

  6. Click Convert.

    This plug-in places copies of your original files in the backup folder and converts all the files you specified in their original location. Once you have run the converter, your files will be setup to use the Java Plug-in.

  7. Click Done when the Progress window shows that all files have been processed.

20.11.4 Deploying Applets

Deploying your applet, or any other Java EE web modules in Oracle Application Server with JDeveloper is a completely automated process.

20.11.4.1 How to Configure an Applet for Deployment

A standalone applet is packaged as a web archive (WAR) file which contains the applet, the Applet HTML file, as well as the standard Java EE web deployment descriptor, web.xml and possibly target-specific deployment descriptors, as well. After you have created the deployment profile and the appropriate deployment descriptor files, you can deploy the application to an application server, or as an archive file.

To configure a web application for deployment:

  1. Create a WAR file deployment profile for your project.

    A profile may have already been created for your project. If you wish to deploy to multiple targets, create a separate profile for each.

  2. Add a web.xml deployment descriptor to your project, if it is not already present.

    Normally, this file is created with the WAR file deployment profile.

Notes:

If you encounter problems when deploying a Swing applet (JApplet), for example, the error "Class not found" is displayed, this may indicate that JDeveloper cannot locate the Swing libraries. Your clients may need to use Sun's Java SE browser plugin or bundle the Swing libraries for JVMs version 1.1 with your applet.

Deployed applet files must reside in a separate location from any other web application files you have deployed.

20.11.4.2 How to Deploy an Applet as a WAR File

You can deploy web application components including applets as a WAR or EAR file to the target application server.

To deploy an applet as a WAR file:

  1. If not already done, configure the applet for deployment.

  2. If not already done, create an application server connection.

  3. In the Navigator, right-click the project and choose Deploy > deployment profile.

  4. In the Deploy dialog, select one of the deployment options:

    • Deploy to application server connection to create the archive type specified in the deployment profile, and deploy it to the application server connection you select or create on the Select Server page of the Deploy dialog.

    • Deploy to EAR file to deploy the project and any of its dependencies (specified in the deployment profile) to an EAR. JDeveloper puts the EAR file in the default directory specified in the deployment profile.

    • Deploy to WAR file to deploy the project to a WAR. JDeveloper puts the WAR file in the default directory specified in the deployment profile.

    Notes:

    The deployed applet files must reside in a separate location from any other web application files you have deployed.

    If you encounter problems when deploying a Swing applet (JApplet), for example, the error "Class not found" is displayed, this may indicate that JDeveloper cannot locate the Swing libraries. You may need to force your clients to use Sun's Java SE browser plugin or bundle the Swing libraries for JVMs version 1.1 with your applet.

20.12 Working with the UI Debugger

In addition to JDeveloper's standard Java and PL/SQL debugger facilities, JDeveloper also provides support for debugging graphical user interfaces (GUIs) specifically for AWT and Swing-based client applications and applets.

The UI Debugger offers an alternative way of debugging a GUI application. Traditional debuggers let you examine the data structure and track program flow. Instead, the UI Debugger lets you examine the GUI structure and the event sequences. The UI debugger helps you to see the relationship between UI components displayed on the screen with the actual data. It will also show you the events that are fired by the UI components, and the listeners that receive the events.

To use the UI Debugger, you need to first download it by choosing Help > Check for Updates and following the instructions in the wizard. For more information on how to install an Oracle JDeveloper Extension, see the Oracle Fusion Middleware Installation Guide for Oracle JDeveloper.

There are no additional special prerequisites for the using the UI Debugger beyond those requirements for using the JDeveloper debugger, other than ensuring that the JDeveloper Runtime library, jdev-remote.jar, is selected in the Project Properties - Libraries page.

Debugging a GUI application can be a challenge since most traditional debuggers do not let you easily examine the tree structure of a GUI application, nor do they display the details of what is displayed by your application.

To start debugging, select a project and choose Run > UI Debug <projectname>.jpr to start debugging.

20.12.1 Working with UI Debugger Windows

You can use the UI Debugger features which are exposed in JDeveloper via three dockable windows. The UI Tree and the UI Outline windows appear automatically when the UI Debugger is started. The Events window appears the first time you track events. You can toggle all three windows by choosing View > UI Debugger - <UI_debugger_window>.

Note:

No information is displayed in the UI Debugger windows until you take a snapshot. Click the Snapshot (F5) button to populate the UI Tree and the UI Outline windows.
  • UI Tree: Displays a hierarchical structure of your application's components and sub-components and their parent-child relationships. Select a component from the tree and right-click to display the context menu options. You will notice that the component is also selected in the UI Outline window.

  • UI Outline: Displays an image or outline image of the application's GUI. Select a component from the graphical representation of the GUI application and right-click to display the context menu options.

    Note:

    Since AWT components may not be painted correctly, Oracle recommends that you work in Outline mode for non-Swing based applications.
  • Events: Displays information about those events you've selected to listen to from the Listeners dialog. The Listener dialog displays when you choose the Events context menu option from either the UI Tree or UI Outline windows. When you select an event in this window, its source component is selected in the tree and outline windows.

20.12.2 How to Start the UI Debugger

Before performing any UI Debugger task, you'll need to first start the UI Debugger.

To start the UI debugger:

  1. Select the project in the navigator that you want to debug.

  2. Select a run configuration. For more information, see Section 19.3, "How to Configure a Project for Running."

  3. Choose Run > UI Debug <projectname>.jpr to start the project's default target and to run the application.

    JDeveloper starts the UI Debugger. The application is launched and the UI Tree and UI Outline windows automatically appear. However, no information is displayed in the UI Debugger windows yet.

  4. After the application is completely launched, go to the dialog or window you want to debug and select it.

  5. From either UI Debugger windows, click the Snapshot (F5) button.

    JDeveloper displays a hierarchical structure of the application in the UI Tree window and displays a graphical representation of the application's user interface in the UI Outline window.

20.12.3 Examining the Application Component Hierarchy

The information in the UI Tree and the UI Outline windows and the relationship between them are always synchronized. Since the information in the UI Tree and the UI Outline windows is identical (only the way they are presented is different), whenever you select a component in the UI Tree hierarchy, JDeveloper locates and highlights the same object in the UI Outline window, and vice versa.

Before examining the application component hierarchy, you must start the UI Debugger and take a snapshot. Whenever the UI of the application is updated, you must click Snapshot again to update the information displayed by the UI Debugger windows.

Ways to examine the application component hierarchy:

  • Use the tree of the UI Tree window to explore the hierarchical structure of the components or use the UI Outline window to locate the components visually.

  • Use the Image and Outline checkboxes at the top of the UI Outline window to toggle respectively the image and the borders of the components.

  • You can use the icons at the bottom of the UI Outline window to zoom in or zoom out of the application image. If the image is larger than the window, you can pan across by clicking and dragging the image.

  • The components that are not selected in the UI Outline window are shaded red.

  • Hidden components are represented by gray text in the UI Tree.

  • You can right-click a component in either windows to display the context menu options. See UI Tree or UI Outline for more information.

20.12.4 How to Display Component Information in the Watches Window

To examine the data associated to a component, you can choose to watch the component in the JDeveloper Watches window. A watch enables you to monitor the changing values of variables or expressions as your program runs.

To display component information in the Watches window:

  1. If not already done, start the UI Debugger and take a snapshot.

  2. Right-click a component either in the UI Tree or the UI Outline window and choose Watch from the context menu.

    The Watches window opens as a tab in the Smart Data window (if it is not already open), and a tree representing the component's structure is displayed in it.

20.12.5 How to Inspect a UI Component in an Inspector Window

You can view the state of a UI component in a JDeveloper Inspector window.

To display a UI component in an Inspector window:

  1. If not already done, start the UI Debugger and take a snapshot.

  2. Right-click a component either in the UI Tree or the UI Outline window and choose Inspect from the context menu.

    The Inspect window opens as a tab in the Smart Data window (if it is not already open), and a tree representing the component's structure is displayed in it.

20.12.6 How to Trace Events Generated by Components

Use the event tracing feature to monitor the firing of selected events generated by UI components. Use this information to determine the content of events, and their sequence.

To trace events generated by components:

  1. If not already done, start the UI Debugger and take a snapshot.

  2. Right-click a component either in the UI Tree or the UI Outline window and choose Trace Events from the context menu.

    The Trace Events dialog opens, displaying a list of the listeners that receive the event types fired by the component.

    Note:

    Event listeners are listed only for UI components that were visible when the snapshot was taken. If subsequent execution have added or removed UI components, the change will not be seen in the list.
  3. (Optional) Select Include Children to also show additional event types fired by the children of the selected component.

  4. In the Listeners dialog, select which event listener(s) you want to trace. For example, if you select FocusListener, all focus events will be traced.

  5. Click OK.

  6. The events fired by the selected listeners are displayed in the Events window. Right-click in the window to Clear the contents of the window or to Remove a specific Listener.

20.12.7 How to Show Event Listeners

Use the show listeners feature to find the recipients of events fired by UI components. Use this information to determine the extent of UI events.

Caution:

Event listeners are listed only for UI components that were visible when the snapshot was taken. If subsequent execution have added or removed UI components, the change will not be seen in the list.

To trace events generated by components:

  1. If not already done, start the UI Debugger and take a snapshot.

  2. Right-click a component either in the UI Tree or the UI Outline window and choose Show Listeners from the context menu.

    The Listeners dialog opens for the selected component, displaying a list of listener types informed by the component, the classes of the registered listeners for each listener type, and the event methods implemented by each class.

    Note:

    The debugger's tracing filter is applied to the listener's list. A listener whose class is excluded by the filter will not be shown.
  3. Select a method.

  4. Click Go To Source.

    An edit window opens, showing the source code for the selected method.

20.12.8 How to Remote Debug GUI Applications

JDeveloper supports remote debugging GUI applications via the command line. To achieve this, you must manually launch the program you want to debug. Once the program is launched and the JDeveloper debugger is attached to it, remote debugging is very similar to local debugging.

Performing remote UI debugging is similar to remote debugging any application. Just make sure that the following requirements are met first:

  • Add the JDeveloper runtime, jdev-remote.jar, to the libraries

  • Specify the UI Debugger agent's main class before your application's main class

To remote debug GUI applications:

  1. Configure your project for debugging, making sure to enable it for remote debugging.

  2. Start your application manually as follows by executing:

    java -XXdebug -cp ...\jdev\lib\jdev-remote.jar 
    oracle.jdevimpl.runner.uidebug.debuggee.Debuggee <MainClass>
    

    where

    • ...\jdev\lib\jdev-remote.jar is the JDeveloper Runtime Library classpath which you must add to the command.

    • oracle.jdevimpl.runner.uidebug.debuggee.Debuggee is the name of the main class of the UI Debugger's agent.

  3. A message similar to the following is printed in the command window:

    *** Port is 4000 ***
    *** Waiting for JVM debugger connection. ***
    
  4. The UI Debugger uses a socket to interact with your application. The default port number for the socket is 4030 but you can specify another port number by inserting -uidport,<port> before the application's main class as follows:

    java -XXdebug -cp ...\jdev\lib\jdev-remote.jar
    oracle.jdevimpl.runner.uidebug.debuggee.Debuggee -uidport,5678 
    mypackage1.Application1
    

    In this case, you will also have to specify the port number when you start the UI Debugger in the JDeveloper IDE.

To Start JDeveloper IDE for Remote UI Debugging:

  1. Select a run configuration that has been set up for remote debugging (Run > Choose Active Run Configuration).

  2. Choose Debug, then UI Debug <project_name>.jpr.

    The main method of your Java application is started.

  3. The Attach to JPDA dialog appears, prompting you to specify a host name and a UI debugger port.

    Unless you have used the -uidport option, you should leave this value to the default 4030.

  4. Your UI debugging session will now behave as if it were performing local UI debugging. You can begin performing any UI debugger task.

20.12.9 Automatic Discovery of Listeners

The list of events that can be tracked by the UI Debugger is not hard-coded but is dynamically discovered at runtime. It is therefore possible to track events fired by any listener, provided that they adhere to the following guidelines:

  • The component class must have public methods to add and remove a listener.

  • The name of the methods must start with add or remove and end with Listener.

  • The return type must be void.

  • The methods must have only one argument.

  • The type of the argument must be an interface that extends java.util.EventListener.

  • The name of the method must be equal to the name of the interface preceded by add or remove.

  • The return type of each method in the specified interface must be void.

  • The method can only have one argument (the event).

  • The type of the argument must be a class accessible as a bean.

  • The return values of the getters can be anything except void. If the type is a non-primitive type, the value that will be shown in the UI Debugger will be the string obtained by calling the object's toString() method.

Examples

  • For example, if you want to define a new event listener of type Xxx, your component must have methods with the following signatures:

    public void addXxxListener(XxxListener); 
    public void removeXxxListener(XxxListener);
    
  • An example of an XxxListener interface could be:

    public interface XxxListener extends java.util.EventListener
    {
       public void methodOne(XxxEvent xxxEvent);
       public void methodTwo(XxxEvent xxxEvent);
       public void methodThree(XxxEvent xxxEvent);
    }
    
  • An example of a XxxEvent class could be:

    public class XxxEvent 
    {
       public int getA(){...} 
       public String getB(){...} 
       public OtherType getC(){...}