Home > Articles > Programming > Java

Java Widget Fundamentals

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book
Widgets are the building blocks of java user interfaces. Learn all about them in this chapter from SWT: The Standard Widget Toolkit, Volume 1.

This chapter provides an overview of the classes contained in the packages org.eclipse.swt.widgets and org.eclipse.swt.events. We begin by defining what a widget is, then cover the fundamental relationships between widgets, and finally cover how widgets interrelate with each other and the user.

1.1 What Is a Widget?

A widget is a graphical user interface element responsible for interacting with the user. Widgets maintain and draw their state using some combination of graphical drawing operations. Using the mouse or the keyboard, the user can change the state of a widget. When a state change occurs, whether initiated by the user or the application code, widgets redraw to show the new state. This is an important distinguishing feature that all widgets share. It means that when you set a property on a widget, you are not responsible for telling the widget to redraw to reflect the change.

1.1.1 Life Cycle

Widgets have a life cycle. They are created by the programmer and disposed of when no longer needed. Because the widget life cycle is so fundamental to the understanding of the Standard Widget Toolkit (SWT), we are going to cover it in detail here.

1.1.2 Creating a Widget

Widgets are created using their constructor, just like any other Java object. Some widget toolkits employ the factory pattern to instantiate their widgets. For simplicity, SWT does not.

When a widget is instantiated, operating system resources are acquired by the widget. This simplifies the implementation of SWT, allowing most of the widget state to reside in the operating system, thus improving performance and reducing memory footprint. [1] There is another important benefit of acquiring operating system resources in the constructor. It gives a clear indication when resources have been allocated. We will see that this is critical in the discussion of widget destruction (see Disposing of a Widget).

Finally, constructors take arguments that generally cannot be changed after the widget has been created. Note that these arguments are create-only from the point of view of the operating system and must be present when the widget is created.

Standard Constructors

Widget is an abstract class, so you will never create a Widget instance. In the discussion that follows, note that references to the class Widget actually apply to the subclasses of Widget. This is because subclasses of Widget share the same constructor signatures, giving widget creation a strong measure of consistency, despite the different kinds of widgets and their implementation.

There are four general forms of widget constructor implemented by the subclasses of the class Widget.

  1. Widget ()

  2. Widget (Widget parent)

  3. Widget (Widget parent, int style)

  4. Widget (Widget parent, int style, int index)

The concept of hierarchy (see Widget Hierarchy) is very important in SWT, so much so that the parent widget is the first parameter in most widget constructors. [2] The following sections describe each of the parameters in detail.

A Word About Parameters, Exceptions, and Error Checking

In SWT, methods that take parameters that are Objects check for null and throw IllegalArgumentException ("Argument cannot be null") when the argument can't be null. Besides being more informative, checking for null helps to ensure consistent behavior between different SWT implementations. Barring unforeseen circumstances, such as catastrophic virtual machine failure, an SWT method will throw only three possible exceptions and errors: IllegalArgumentException, SWTException, and SWTError. Anything else is considered to be a bug in the SWT implementation.

The Parent Parameter

Widgets cannot exist without a parent, and the parent cannot be changed after a widget is created. [3] This is why the parent is present in almost every constructor. The type of parent depends on the particular widget. For example, the parent of a menu item must be a menu and cannot be a text editor. Strong typing in the constructor enforces this rule. Code that attempts to create a menu item with a text editor parent does not compile, making this kind of programming error impossible.

It is also possible to query the parent of a widget using getParent() but this method is not found in the class Widget.

Why Is getParent() Not Implemented in Widget?

We could have implemented getParent() in class Widget but the method would need to return a Widget. This would require the programmer to cast the result to the appropriate type, despite the fact that the correct type was provided in the constructor. By implementing getParent() in each subclass, the type information that was specified when the widget was created is preserved. One of the design goals of SWT is to preserve as much type information as possible in the API, reducing the need for application programs to cast.

The Style Parameter

Styles are integer bit values used to configure the behavior and appearance of widgets. They specify create-only attributes, such as choosing between multiple- and single-line editing capability in a text widget. Because these attributes cannot be changed after creation, the style of a widget cannot be changed after it has been created. Style bits provide a compact and efficient method to describe these attributes.

All styles are defined as constants in the class org.eclipse.swt.SWT.

Class SWT

SWT uses a single class named (appropriately) SWT to share the constants that define the common names and concepts found in the toolkit. This minimizes the number of classes, names, and constants that application programmers need to remember. The constants are all found in one place.

As expected, you can combine styles by using a bitwise OR operation. For example, the following code fragment creates a multiline text widget that has a border and horizontal and vertical scroll bars.

Text text = new Text (parent,
    SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);

The list of the style constants that are applicable to each widget is described in the Javadoc for the widget. Styles that are defined in a given superclass are valid for the subclasses unless otherwise noted. The constant SWT.NONE is used when there are no applicable style bits.

The widget style can be queried after it has been created using getStyle().

  • getStyle() Returns the actual style of the widget represented using a bitwise OR of the constants from class SWT. Note that this can be different from the value that was passed to the constructor because it can include defaults provided by the widget implementation. In addition, if a style requested in the constructor cannot be honored, the value returned by getStyle() will not contain the bits. This can happen when a platform does not support a particular style.

The following code fragment uses a bitwise AND to test to see whether a text widget displays and can edit only a single line of text.

if ((text.getStyle () & SWT.SINGLE) != 0) {
    System.out.println ("Single Line Text");
}

The Position Parameter

The position parameter allows you to create a widget at a specific index in the list of children or by the parent. [4] The other children in the list are shifted to make room for the new widget. For example, the position parameter could be used to create a menu item and make it the third item in a menu. By default, if the position parameter is not provided, the child is placed at the end of the list.

Why is there no widget "add()" method to add a child to the children list of its parent? For an add() method to do something reasonable, it would require that you be able to remove a widget from the children list without destroying it. Given that a widget cannot exist without a parent, this would leave the child in a state where it knows about its parent but the parent does not know about the child.

Convenience Constructors—Just Say No

Some programmers demand convenience constructors using arguments such as, "Every time a button is created, I always set the text so there should be a button constructor that takes a string." Although it is tempting to add convenience constructors, there is just no end to them. Buttons can have images. They can be checked, disabled, and hidden. It is tempting to provide convenience constructors for these properties, as well. When a new API is defined, even more convenience constructors are needed. To minimize the size of the widget library and provide consistency, SWT does not normally provide convenience constructors.

1.1.3 Disposing of a Widget

When a widget is no longer needed, its dispose() method must be explicitly called.

  • dispose() Hides the widget and its children, and releases all associated operating system resources. In addition, it removes the widget from the children list of its parent. All references to other objects in the widget are set to null, facilitating garbage collection. [5]

SWT does not have a widget remove() method for the same reason that there is no add() method: It would leave the child in a state where it knows about its parent but the parent does not know about the child. Because widgets are alive for exactly the duration that they are referenced by their parents, implicit finalization (as provided by the garbage collector) does not make sense for widgets. Widgets are not finalized. [6]

Accessing a widget after it has been disposed of is an error and causes an SWTException ("Widget is disposed") to be thrown. The only method that is valid on a widget that has been disposed of is:

  • isDisposed() Returns true when the widget has been disposed of. Otherwise, returns false.

If you never dispose of a widget, eventually the operating system will run out of resources. In practice, it is hard to write code that does this. Programmers generally do not lose track of their widgets because they require them to present information to the user. Users generally control the life cycle of top-level windows—and the widgets they contain—by starting applications and clicking on "close boxes."

When a widget is disposed of, a dispose event is sent, and registered listeners are invoked in response. For more on this, see the section Events and Listeners.

1.1.4 Rules for Disposing of Widgets

There are only two rules that you need to know to determine when to dispose of a particular widget. Please excuse the references to specific classes and methods that have yet to be discussed. They will be described in detail later in the book. It is more important at this time that the "rules" are complete.

Rule 1:

If you created it, you dispose of it. SWT ensures that all operating system resources are acquired when the widget is created. As we have already seen, this happens in the constructor for the widget. What this means is that you are responsible for calling dispose() on SWT objects that you created using new. SWT will never create an object that needs to be disposed of by the programmer outside of a constructor.

Rule 2:

Disposing a parent disposes the children. Disposing of a top-level shell will dispose of its children. Disposing of a menu will dispose of its menu items. Disposing of a tree widget will dispose of the items in the tree. This is universal.

There are two extensions to Rule 2. These are places where a relationship exists that is not a parent-child relationship but where it also makes sense to dispose of a widget.

Rule 2a:

Disposing a MenuItem disposes the cascade Menu.

  • MenuItem.setMenu() Disposing of a MenuItem that has a submenu set with the setMenu() method disposes of the submenu. This is a natural extension of Rule 2. It would be a burden to the programmer to dispose of each individual submenu. It is also common behavior in most operating systems to do this automatically. [7]

Rule 2b:

Disposing a control disposes the pop-up Menu.

  • Control.setMenu() Disposing of a control that has a pop-up menu assigned using the setMenu() method disposes the pop-up menu. Many application programmers expected this behavior, even though the operating systems do not do it automatically. We added this rule because too many application programs temporarily leaked pop-up menus. [8]

Another way to remember the extensions to Rule 2 is to notice that both extensions concern instances of the class Menu when used with the setMenu() method. For more information about menus, see Classes Menu and MenuItem in the ToolBars and Menus chapter.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus