www espirity com Building GUIs with SWT Dwight

www. espirity. com Building GUIs with SWT Dwight Deugo (dwight@espirity. com) Nesa Matic (nesa@espirity. com)

Additional Contributors n Carolyn Mac. Leod, IBM 2 © 2003 -2004, Espirity Inc.

Module Overview 1. SWT Basics 2. GUI Patterns 3 © 2003 -2004, Espirity Inc.

Module Road Map 1. SWT Basics § § § 2. SWT applications SWT terminology SWT layouts GUI Patterns 4 © 2003 -2004, Espirity Inc.

SWT n Delivers native widget functionality for the Eclipse platform in an operating system independent manner q n Analogous to AWT/Swing in Java Delivers functionality using a small and consistent API q API is implemented on different platforms using a combination of Java code and JNI natives specific to each platform 5 © 2003 -2004, Espirity Inc.

SWT Application n Core Components q n Widgets, Layouts, Events Structure q q q q Create a Display Create a Shell which serves as the main window Create other widgets that are needed inside the shell Initialize the state for the widgets Register listeners for widget events Open the shell window Run the event dispatching loop until an exit condition occurs Dispose the display 6 © 2003 -2004, Espirity Inc.
![SWT Application Example public static void main(String[] args) { Display display = new Display(); SWT Application Example public static void main(String[] args) { Display display = new Display();](http://slidetodoc.com/presentation_image_h2/b8ffb5ad9a5c6d855e5a12e54ca7a966/image-7.jpg)
SWT Application Example public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell. set. Layout(new Row. Layout()); Label label = new Label(shell, SWT. CENTER); label. set. Text("It Works"); shell. open(); while (!shell. is. Disposed ()) { if (!display. read. And. Dispatch ()) display. sleep (); } display. dispose (); } 7 © 2003 -2004, Espirity Inc.

Terminology n Display q q n Shell q n The connection between SWT and the underlying platform's GUI system Used to manage the platform event loop and control communication between the UI thread and other threads Window managed by the OS platform window manager Composite q Widget that has widget children 8 © 2003 -2004, Espirity Inc.

Layouts… n n n Controls the position and size of children in a Composite Layout classes are subclasses of the abstract class Layout SWT provides several standard layout classes, and you can write custom layout classes: q q Fill. Layout, places equal-sized widgets in a single row or column Row. Layout, places widgets in a row or rows Grid. Layout, places widgets in a grid Form. Layout, places widgets by creating attachments for each side 9 © 2003 -2004, Espirity Inc.

Working with Layouts n You need to import the SWT layout package: q n import org. eclipse. swt. layout. *; To set the Composite widget’s layout use widget’s set. Layout(Layout) method Display display = new Display(); Shell shell = new Shell(display); shell. set. Layout(new Fill. Layout()); 10 © 2003 -2004, Espirity Inc.

Layout Data n A layout class uses a layout data class q q q n Row. Layout -> Row. Data Grid. Layout -> Grid. Data Form. Layout -> Form. Data Set a widget’s layout data class as follows: Button button = new Button(shell, SWT. PUSH); button. set. Layout. Data(new Row. Data(10, 20)); 11 © 2003 -2004, Espirity Inc.

Fill. Layout n n n Lays out widgets in a row or column All widgets the same size No wrapping You cannot specify margins or spacing Use it to: Lay out buttons in a task bar or tool bar q Stack checkboxes in a Group q 12 © 2003 -2004, Espirity Inc.

Fill. Layout Example… Display display = new Display(); Shell shell = new Shell(display); Fill. Layout fill. Layout = new Fill. Layout(); fill. Layout. type = SWT. VERTICAL; shell. set. Layout(fill. Layout); new Button(shell, SWT. PUSH). set. Text("1'st Button"); new Button(shell, SWT. PUSH). set. Text("Big Button"); new Button(shell, SWT. PUSH). set. Text("Button 3"); new Button(shell, SWT. PUSH). set. Text("Last Button"); shell. pack(); shell. open(); 13 © 2003 -2004, Espirity Inc.

…Fill. Layout Example fill. Layout. type = SWT. VERTICAL; fill. Layout. type = SWT. HORIZONTAL; 14 © 2003 -2004, Espirity Inc.

Row. Layout n n n Row. Layout has the ability to wrap Provides configurable margins and spacing Various fields can be set The height and width of each widget can be specified q Use the Row. Data object q 15 © 2003 -2004, Espirity Inc.

Row. Layout Example … Row. Layout row. Layout = new Row. Layout(); row. Layout. wrap = true; row. Layout. pack = true; row. Layout. justify = true; row. Layout. type = SWT. HORIZONTAL; row. Layout. margin. Left = 4; row. Layout. margin. Top = 4; row. Layout. margin. Right = 4; row. Layout. margin. Bottom = 4; row. Layout. spacing = 0; shell. set. Layout(row. Layout); 16 © 2003 -2004, Espirity Inc.

…Row. Layout Example… row. Layout. wrap = false; row. Layout. pack = false; row. Layout. justify = false; 17 © 2003 -2004, Espirity Inc.

…Row. Data Example Row. Layout row. Layout = new Row. Layout(); shell. set. Layout(row. Layout); Button button 1 = new Button(shell, SWT. PUSH); button 1. set. Text("First"); button 1. set. Layout. Data(new Row. Data(50, 100)); Button button 2 = new Button(shell, SWT. PUSH); button 2. set. Text("Second"); button 2. set. Layout. Data(new Row. Data(200, 400)); 18 © 2003 -2004, Espirity Inc.

Grid. Layout n n n Most used layout Most complicated too Children of a Composite laid out in a grid q n n columns/rows size to fit the children they contain Various fields can be set Widgets it lays out can have an associated Grid. Data q Provides the ability to configure Grid. Data for each widget 19 © 2003 -2004, Espirity Inc.

Grid. Layout Example Grid. Layout grid. Layout = new Grid. Layout(); grid. Layout. num. Columns = 2; shell. set. Layout(grid. Layout); new Button(shell, SWT. PUSH). set. Text("B 1"); new Button(shell, SWT. PUSH). set. Text("Second Button"); new Button(shell, SWT. PUSH). set. Text("Third Button"); new Button(shell, SWT. PUSH). set. Text("B 4"); new Button(shell, SWT. PUSH). set. Text("B 5"); new Button(shell, SWT. PUSH). set. Text("Button Number 6"); 20 © 2003 -2004, Espirity Inc.

Grid. Layout Fields n Fields make. Columns. Equal. Width field forces the columns to be the same width q margin. Width specifies left and right margins q margin. Height specifies top and bottom margins q horizontal. Spacing and vertical. Spacing can be specified independently q 21 © 2003 -2004, Espirity Inc.

Grid. Data n n Represents layout data object associated with Grid. Layout Set a widget’s Grid. Data object using the set. Layout. Data method Button a. Button = new Button(shell, SWT. PUSH); a. Button. set. Text("First. Button"); a. Button. set. Layout. Data(new Grid. Data()); 22 © 2003 -2004, Espirity Inc.

Grid. Data Fields… n horizontal. Alignment: specifies where to place a widget horizontally and/or vertically within its grid cell q n horizontal. Indent: allows you to move a widget to the right by a specified number of pixels q n BEGINNING, CENTER, END, FILL Usually useful when the horizontal. Alignment is BEGINNING horizontal. Span and vertical. Span: lets widgets occupy more than one grid cell 23 © 2003 -2004, Espirity Inc.

…Grid. Data Fields n n grab. Excess. Horizontal. Space and grab. Excess. Vertical. Space: allow widgets to grow if their containing Composite grows width. Hint and height. Hint: identify a widget’s number of pixels wide or tall 24 © 2003 -2004, Espirity Inc.

Grid. Data Example… Grid. Layout grid. Layout = new Grid. Layout(); grid. Layout. num. Columns = 3; shell. set. Layout(grid. Layout); … Text user. Name = new Text(shell, SWT. SINGLE | SWT. BORDER); Grid. Data grid. Data = new Grid. Data(Grid. Data. HORIZONTAL_ALIGN_FILL); grid. Data. horizontal. Span = 2; user. Name. set. Layout. Data(grid. Data); … Each widget must have its own instance of grid data 25 © 2003 -2004, Espirity Inc.

…Grid. Data Example… Combo sex = new Combo(shell, SWT. NONE); sex. set. Items(new String [] {"Male", "Female"}); grid. Data = new Grid. Data(Grid. Data. HORIZONTAL_ALIGN_FILL); grid. Data. horizontal. Span = 2; sex. set. Layout. Data(grid. Data); new Label(shell, SWT. NONE). set. Text("Photo: "); Canvas photo = new Canvas(shell, SWT. BORDER); grid. Data = new Grid. Data(Grid. Data. FILL_BOTH); grid. Data. width. Hint = 80; grid. Data. height. Hint = 80; grid. Data. vertical. Span = 3; photo. set. Layout. Data(grid. Data); 26 © 2003 -2004, Espirity Inc.

…Grid. Data Example 27 © 2003 -2004, Espirity Inc.

Form. Layout n Creates Form. Attachments for sides of the widget Stores the attachments in the layout data q Attach side to a position in the parent Composite or to another widget within the layout q n Allows you to fully specify the placement of widgets in the layout 28 © 2003 -2004, Espirity Inc.

Form. Layout Fields n The margin fields in Form. Layout are the same as in Grid. Layout margin. Width: defines left and right margins q margin. Height: defines top and bottom margins q n Margins can also be defined on a per-widget basis in the attachments q Form. Layout margins are 0 by default 29 © 2003 -2004, Espirity Inc.

Form. Data Fields n n left, right, top and bottom fields of Form. Data specify the Form. Attachment objects There are many ways that a side can be attached to a position in the parent Composite: q q n n Edge of the Composite Adjacent side of another widget The opposite side of another widget Centered on another widget To attach to an edge of the Composite, the percentage is either 0% or 100% width and height fields of Form. Data specify the requested width and the height of the widget 30 © 2003 -2004, Espirity Inc.

Attaching to a Position n Set the top of the Button to a position that represents 50% of the height of the parent Composite (a Shell), with an offset of 0 shell. set. Layout(new Form. Layout()); Button a. Button = new Button(shell, SWT. PUSH); a. Button. set. Text("First Button"); Form. Data form. Data = new Form. Data(); form. Data. top = new Form. Attachment(50, 0); a. Button. set. Layout. Data(form. Data); 31 © 2003 -2004, Espirity Inc.

Attaching to a Parent n Attaches the right side of the Button to the right edge of the parent (a Shell), with an offset of 5 pixels shell. set. Layout(new Form. Layout()); Button a. Button = new Button(shell, SWT. PUSH); a. Button. set. Text("First Button"); Form. Data form. Data = new Form. Data(); form. Data. right = new Form. Attachment(100, -5); a. Button. set. Layout. Data(form. Data); 32 © 2003 -2004, Espirity Inc.

Attaching to Another Widget n a. Button will move so that its top side is always positioned at 30% of the Shell, and another. Button will move so that its top side is always 20 pixels below the adjacent (bottom) side of a. Button shell. set. Layout(new Form. Layout()); Button a. Button = new Button(shell, SWT. PUSH); Button another. Button = new Button(shell, SWT. PUSH); a. Button. set. Text("First Button"); another. Button. set. Text("Button: 2"); Form. Data form. Data 1 = new Form. Data(); Form. Data form. Data 2 = new Form. Data(); form. Data 1. top = new Form. Attachment(30, 0); a. Button. set. Layout. Data(form. Data 1); form. Data 2. top = new Form. Attachment(a. Button, 20); another. Button. set. Layout. Data(form. Data 2); a. Button. set. Layout. Data(form. Data 1); 33 © 2003 -2004, Espirity Inc.

Module Road Map 1. SWT 2. GUI Patterns § § View Event Handler Pattern Complete Update Pattern 34 © 2003 -2004, Espirity Inc.

GUI Patterns n n n View Event Handler Complete Update Pattern Goal q Describe how to build GUIs that are easy to debug, modify and maintain 35 © 2003 -2004, Espirity Inc.

Global Context n n n You are developing a new View or View. Part subclass The widgets contained in your new view have a low degree of dependencies between one another The widgets use the Observer pattern to notify the views of changes 36 © 2003 -2004, Espirity Inc.

Global Forces n n n n A view’s functionality changes often A significant period may elapse between the time a developer last worked on a view and the time he is making changes to it The original developer of a view is not always the same person that maintains or extends it Tightly coupled widgets are difficult to merge or split Visual containers that have many constraints between their visual components, such as tree views and grids, are difficult and time consuming to update A large percentage of time is required for GUI development Unique view designs are more difficult to support than consistent ones Since a view is a user’s entry point into an application, it must be user friendly 37 © 2003 -2004, Espirity Inc.

View Event Handler Pattern… n Context q q You have incorporated the Observer pattern into your view’s design Your view is interested in receiving event messages from its observable widgets when specific events occur in them Your view needs to collaborate with one or more model objects in order to handle these notification messages and then update its widgets in response You want your view to update its widgets in an organized, linear manner, so that regions of the view update together rather than in an apparent random manner 38 © 2003 -2004, Espirity Inc.

…View Event Handler Pattern… n Problem q How should a view handle event notifications from its observable widgets So it does not create any updating dependencies between the methods ; The number of updates to the widgets is minimized? ; 39 © 2003 -2004, Espirity Inc.

…View Event Handler Pattern… n Forces q q Many observable widgets can generate identical event messages You can use a case statement to determine which widget sent the event message and how to process it in a single handler method Setting flags when handling event messages in order to decide which observable widget to update ensures that you don't perform any redundant updates If the handling of a single event message results in many changes to your view’s model, the MVC pattern forces the model to send notification messages to its corresponding widgets several times 40 © 2003 -2004, Espirity Inc.

…View Event Handler Pattern n Solution q q q In your view, create and register a handler method for each event message from your widgets Do not register your views with the models Your view’s handler method should pull information from the appropriate widgets when invoked and then invoke the corresponding services in the models Your handler method should not do any updating of the widgets itself Have your handler use a single update method that is responsible for updating all widgets 41 © 2003 -2004, Espirity Inc.

View Event Handler Pattern Example public class To. Do. List. View { private static String EMPTYSTRING = ""; private private Display display; Shell shell; Text to. Do. Item. Text; List todo. Items. List; Button delete. Button, add. Button; private String new. Item; private Vector items; private String selected. Item ; … 42 © 2003 -2004, Espirity Inc.

Event Handling in Java n n Anything that happens in UI causes an event to occur Any object can be notified of the event n Object must be registered as a listener for the event listener 1 UI component event 43 listener 2 listener 3 listener 4 … listener n © 2003 -2004, Espirity Inc.

Listeners n Listeners are Java mechanism for event handling q Registering listeners means that object that registers them is interested in specific event to. Do. Item. Text. add. Modify. Listener( new To. Do. Item. Text. Modify. Listener()); todo. Items. List. add. Selection. Listener( new Todo. Items. List. Selection. Listener()); add. Button. add. Selection. Listener( new Add. Button. Selection. Listener()); delete. Button. add. Selection. Listener( new Delete. Button. Selection. Listener()); 44 © 2003 -2004, Espirity Inc.

Inner Classes n Classes that are defined within other classes They can be used only within the class where they are defined q Anonymous inner classes are inner classes that have no name q n Commonly used in: Concurrent programming (multi-threading) q Event handling q ; Using inner classes keeps the code that handles the event in the class that is interested in the event 45 © 2003 -2004, Espirity Inc.

Handling Events n Listeners implement event handling public class To. Do. List. View { … public class Add. Button. Selection. Listener extends Selection. Adapter { public void widget. Selected(Selection. Event event) { if (!get. New. Item(). equals(EMPTYSTRING)){ get. Items(). add(get. New. Item()); set. New. Item(EMPTYSTRING); } update(); } } … } 46 © 2003 -2004, Espirity Inc.

Complete Update Pattern… n Context q n Used the View Event Handler pattern to develop your view that contains a small number of widgets that can be updated simultaneously in a reasonable amount of time Problem q How do you structure a view’s update mechanism? 47 © 2003 -2004, Espirity Inc.

…Complete Update Pattern… n Forces q q q Changes in the view's model objects may be the result of the view’s action or of another object’s action the view does not know about Developer created flags indicating which widgets require updating in a view are complicated to understand for both the immediate and future developers You are not always the one who will maintain your views so the view's logic must be easily understood You can often improve performance by using tricky implementation techniques These tricks often complicate your code by making it less easy to read and comprehend You do not always know what has changed in your view’s models or which widgets need updating 48 © 2003 -2004, Espirity Inc.

…Complete Update Pattern… n Solution q Assume the entire view is out-of-date and update everything q Write a specialized write update method for each region of your view q Each specialized update method is responsible for updating its corresponding widgets from information in the models q Permit each specialized update method to load model information directly into the widgets or compute the contents on the fly q Write a single, main update method that invokes all of the specialized update methods q You can still be efficient by not loading model information that has not changed 49 © 2003 -2004, Espirity Inc.

Complete Update Pattern Example… n Single update method private void update(){ update. Add. Button(); update. Delete. Button(); update. To. Do. Item. Text(); update. Todo. Items. List(); } 50 © 2003 -2004, Espirity Inc.

…Complete Update Pattern Example… n Update methods helpers private void update. Delete. Button(){ delete. Button. set. Enabled(!get. Selected. Item(). equals(EMPTYSTRING)); } private void update. Add. Button(){ add. Button. set. Enabled(!get. New. Item(). equals(EMPTYSTRING)); } private void update. To. Do. Item. Text(){ if(!to. Do. Item. Text. get. Text(). equals(get. New. Item())) to. Do. Item. Text. set. Text(get. New. Item()); } 51 © 2003 -2004, Espirity Inc.
![…Complete Update Pattern Example private void update. Todo. Items. List() { String [] display. …Complete Update Pattern Example private void update. Todo. Items. List() { String [] display.](http://slidetodoc.com/presentation_image_h2/b8ffb5ad9a5c6d855e5a12e54ca7a966/image-52.jpg)
…Complete Update Pattern Example private void update. Todo. Items. List() { String [] display. Items; Enumeration enumeration; int index; if(!(todo. Items. List. get. Items(). length == get. Items(). size())){ display. Items = new String[items. size()]; enumeration = get. Items(). elements(); index = 0; while (enumeration. has. More. Elements()){ display. Items[index] = (String)enumeration. next. Element(); index++; } todo. Items. List. set. Items(display. Items); } } 52 © 2003 -2004, Espirity Inc.

Threading Issues… n n Applications can not call UI code from a non. UI thread directly Must provide a Runnable that calls the UI code q n Runnable interface is used for Java threading support Display class used to execute runnables sync. Exec(Runnable) q async. Exec(Runnable) q 53 © 2003 -2004, Espirity Inc.

…Threading Issues n sync. Exec(Runnable) q q q n Use when the application code in the non-UI thread depends on the return value from the UI code Ensure that runable runs to completion before returing to caller SWT blocks caller until runnable completes async. Exec(Runnable) q q Use when the application needs to perform some UI operations, but is not dependent upon the operations being completed before continuing SWT does not block caller" under async. Exec 54 © 2003 -2004, Espirity Inc.

Threading Pattern Example Display. get. Default (). async. Exec (new Runnable () { public void run () { update(); }}); 55 © 2003 -2004, Espirity Inc.

Magic n To run an SWT standalone application you need the following VM argument supplied in the Run window (note forward /’s): q q -Djava. library. path="C: /Program Files/eclipse/plugins/org. eclipse. swt. win 32_3. 0. 0/os/win 32/x 86" where C: /Program Files/eclipse is replaced by your Eclipse install directory 56 © 2003 -2004, Espirity Inc.

Module Summary n In this module we have: Discussed SWT, native widget functionality for the Eclipse platform q Examined different techniques for laying out your views using layout manager q Fill. Layout ; Row. Layout ; Grid. Layout ; Form. Layout ; q Described how to build maintainable GUI using patterns 57 © 2003 -2004, Espirity Inc.

Labs Slide! Lab: Building GUIs with SWT 58 © 2003 -2004, Espirity Inc.

References n Understanding Layouts in SWT http: //www. eclipse. org/articles/Understanding%20 Layouts. htm 59 © 2003 -2004, Espirity Inc.
- Slides: 59