Home > Articles > Programming > Java

Java Widget Fundamentals

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 is from the book

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,

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020