Browse DevX
Sign up for e-mail newsletters from DevX


Use SWT Listener Classes Effectively for Responsive Java UIs

By using the SWT listener classes effectively as this article prescribes, you can win the hearts of your Java application users with highly responsive GUIs.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

nderstanding the SWT listener classes and their usage is essential to building complex, highly responsive user interfaces for Java applications. The listener classes in SWT are classified into two types:
  • Untyped listener API—the framework to write your own listener classes.
  • Typed listener API—the internal implementation of SWT.

The SWT Control class, the abstract superclass of all windowed user interface classes, defines all the add/remove listener methods but it does not implement them. The subclasses provide the actual implementation of these methods. For example, SWT allows you to add any listener to the Label widget but doesn't generate any events when a user clicks the Label, because Label does not define any functionality for these methods. So it is up to the developer to know which listeners work with each widget.

Thankfully, SWT provides a flexible way to manage resources by enabling the removal of unnecessary listeners from the widgets. This is particularly useful for developing SWT applications on memory-constrained, small-footprint applications such as wireless connectivity applications.

This article introduces (with simple examples) the important listener classes, emphasizing those that are new to SWT (not provided in Swing). It concludes a three-article series on SWT development that began with "SWT Creates Fast, Native-looking GUIs for Your Java Apps" and "You Don't Have to Swing to Make Great Java UIs".

Untyped Listener API
The SWT untyped listener API provides three important classes that you can use to write your own listeners:

  • Event
    Instances of this class provide a description of a particular event that occurred within SWT. The SWT untyped listener API uses these instances for all event dispatching. Event provides fields like type, widget, time etc to register all the data about the event.
  • Listener
    Any class that implements this interface must define the handleEvent method. When an event that the receiver has registered for occurs, handleEvent is invoked.
  • Widget
    Any listener class can be added to a widget using the addListener (int eventType, Listener handler) method and removed using the removeListener (int eventType, Listener handler) method. When the specified event occurs, handleEvent(...) is sent to the listener instance.

In the example code, the shell implements a custom mouse listener to capture the MouseUp, MouseDown, and MouseMove events.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date