33
SWT TUTORIAL SWT TUTORIAL By Kalman Hazins By Kalman Hazins ([email protected]) ([email protected])

SWT TUTORIAL

  • Upload
    tim

  • View
    105

  • Download
    2

Embed Size (px)

DESCRIPTION

By Kalman Hazins ([email protected]). SWT TUTORIAL. Links. Tutorials: http://www.cs.umanitoba.ca/~eclipse/ Additional tutorials: http://www.developer.com/java/other/article.php/10936_3330861_1 Code examples: - PowerPoint PPT Presentation

Citation preview

Page 1: SWT TUTORIAL

SWT TUTORIALSWT TUTORIAL

By Kalman HazinsBy Kalman Hazins

([email protected])([email protected])

Page 2: SWT TUTORIAL

LinksLinks Tutorials:Tutorials: http://www.cs.umanitoba.ca/~eclipse/ Additional tutorials:Additional tutorials: http://www.developer.com/java/other/article.php/10936_3330861_1 Code examples:Code examples: http://www.java2s.com/ExampleCode/SWT-JFace-Eclipse/CatalogS

WT-JFace-Eclipse.htm http://www.eclipse.org/swt/ Eclipse - SWT Gui builders:Eclipse - SWT Gui builders:

Jigloo - Jigloo - http://www.cloudgarden.com/jigloo Eclipse ve (visual editor)Eclipse ve (visual editor) SwtGuiBuilder (trial)SwtGuiBuilder (trial)

Additional free IDEs with builders– Jdeveloper, NetBeans mattiseAdditional free IDEs with builders– Jdeveloper, NetBeans mattise

Page 3: SWT TUTORIAL

AgendaAgenda

Brief History of Java GUIBrief History of Java GUI Installing SWTInstalling SWT

Creating widgetsCreating widgets SWT LayoutsSWT Layouts Event Handling Event Handling

Sample Application Sample Application

Page 4: SWT TUTORIAL

History of Java GUIHistory of Java GUI AWT – Abstract Windowing ToolkitAWT – Abstract Windowing Toolkit

First released in 1995 as part of JDK 1.0 by SunFirst released in 1995 as part of JDK 1.0 by Sun Heavyweight GUI componentsHeavyweight GUI components – a Java component creates a peer – a Java component creates a peer

component on the operating system and the peer draws itself.component on the operating system and the peer draws itself. Least Common Denominator problem –Least Common Denominator problem – for simple GUI components for simple GUI components

creating a peer works, what about the components that are only creating a peer works, what about the components that are only available on some platforms and not others? If you want to write code available on some platforms and not others? If you want to write code that’s truly portable – you have to use components that are available on that’s truly portable – you have to use components that are available on all platformsall platforms

The logic makes sense – but how do you develop a serious application The logic makes sense – but how do you develop a serious application using just the basic components (available on all platforms)?using just the basic components (available on all platforms)?

You don’t … You don’t … Enter Enter SwingSwing

Page 5: SWT TUTORIAL

History of Java GUI (Cont.)History of Java GUI (Cont.)

Swing (JFC – Java Foundation Classes)Swing (JFC – Java Foundation Classes) Released in 1998 as part of JDK 1.1Released in 1998 as part of JDK 1.1 Lightweight GUI components – Lightweight GUI components – no need for operating system no need for operating system

“peer”-based drawing. Let’s draw the components ourselves. “peer”-based drawing. Let’s draw the components ourselves. Lightweight – there is no actual weight (operating system Lightweight – there is no actual weight (operating system component) behind the Java component.component) behind the Java component.

Nice toolkit with enhanced Model-View-Controller architecture Nice toolkit with enhanced Model-View-Controller architecture and superior graphics 2D library. and superior graphics 2D library.

Portable? You bet. Any problems? Now that you are not actually Portable? You bet. Any problems? Now that you are not actually using the operating system components – you are just mimicking using the operating system components – you are just mimicking the behavior of the operating system. Hence, the look and feel the behavior of the operating system. Hence, the look and feel as well as the response speed are not the same. as well as the response speed are not the same.

Swing has gotten much better with release 1.4.2 and 1.5 of SDKSwing has gotten much better with release 1.4.2 and 1.5 of SDK Still, very few commercial applications are written in Swing.Still, very few commercial applications are written in Swing.

Page 6: SWT TUTORIAL

History of Java GUI (Cont.)History of Java GUI (Cont.) SWT (Standard Widget Toolkit)SWT (Standard Widget Toolkit)

GUI toolkit released in November 2001GUI toolkit released in November 2001 Was initially designed to write the now extremely famous and Was initially designed to write the now extremely famous and

popular Eclipse IDEpopular Eclipse IDE “ “Best of both worlds” approach – use native functionality when Best of both worlds” approach – use native functionality when

available, and Java implementation when unavailableavailable, and Java implementation when unavailable Takes on the Takes on the appearanceappearance and and behaviorbehavior of the native platform of the native platform Because of its close bond with the operating system, SWT Because of its close bond with the operating system, SWT

needs to be ported separately for every platformneeds to be ported separately for every platform Currently, implementations of SWT are already available for all Currently, implementations of SWT are already available for all

major desktop operating systems and some handheld devicesmajor desktop operating systems and some handheld devices The code YOU write will be portable for all the platforms that The code YOU write will be portable for all the platforms that

have SWT implementations for them (unless you decide to do have SWT implementations for them (unless you decide to do some platform specific stuff like OLE on windows) some platform specific stuff like OLE on windows)

http://www.eclipse.org/swt/ - SWT home pagehttp://www.eclipse.org/swt/ - SWT home page

Page 7: SWT TUTORIAL

Installing SWTInstalling SWT

To compile and run SWT applications you need To compile and run SWT applications you need 1.1. SWT jars (usually just SWT jars (usually just swt.jarswt.jar))2.2. SWT native librariesSWT native libraries

Detailed Instructions on obtaining and “installing”Detailed Instructions on obtaining and “installing”1.1. Go to http://www.eclipse.org/downloads/index.php and follow one Go to http://www.eclipse.org/downloads/index.php and follow one

of the many mirror linksof the many mirror links2.2. This will bring you to another page, where you want to follow the This will bring you to another page, where you want to follow the

“Latest Release” link“Latest Release” link3.3. This should bring you to a page which will say “Release Build: “ in This should bring you to a page which will say “Release Build: “ in

bold letters on the very topbold letters on the very top4.4. Scroll down to the bottom of the page till you see “SWT Binary Scroll down to the bottom of the page till you see “SWT Binary

and Source” sectionand Source” section5.5. Pick the platform you intend to develop on from the list (e.g. Pick the platform you intend to develop on from the list (e.g.

Windows XP) and click on “(http)” to start downloading the zip fileWindows XP) and click on “(http)” to start downloading the zip file6.6. Extract the contents of the zip file into a directory and you are Extract the contents of the zip file into a directory and you are

ready for the final step(s) (let’s say our directory path is C:\SWT)ready for the final step(s) (let’s say our directory path is C:\SWT)

Page 8: SWT TUTORIAL

Installing SWT (Cont.)Installing SWT (Cont.)

7.7. You need to include swt.jar (and possibly other jars) from the C:\SWT You need to include swt.jar (and possibly other jars) from the C:\SWT folder in your classpath (for an example on setting classpath see folder in your classpath (for an example on setting classpath see http://www.moreservlets.com/Using-Tomcat-4.html#Set-CLASSPATHhttp://www.moreservlets.com/Using-Tomcat-4.html#Set-CLASSPATH))

8.8. You also need to include the native library files (e.g. *.dll) from C:\You also need to include the native library files (e.g. *.dll) from C:\SWT in your java.library.path. SWT in your java.library.path.

a.a. The easiest way to do this one is to execute the following The easiest way to do this one is to execute the following command from a regular java programcommand from a regular java program

System.out.println(System.getProperty(“java.library.path”));System.out.println(System.getProperty(“java.library.path”));

which will give you a list of the directories in your “library path”. which will give you a list of the directories in your “library path”. You can then copy the native library files from C:\SWT to one of You can then copy the native library files from C:\SWT to one of those directories. those directories.

-OR- -OR-

b.b. Simply provide the path when running javaSimply provide the path when running java

java –Djava.library.path=C:\SWT classnamejava –Djava.library.path=C:\SWT classname

Page 9: SWT TUTORIAL

Creating WidgetsCreating Widgets SWT Javadoc - SWT Javadoc - http://www.jlab.net/eclipse/doc/3.1/index.htmlhttp://www.jlab.net/eclipse/doc/3.1/index.html Simplest SWT program (explained over the next few slides)Simplest SWT program (explained over the next few slides)

1.1. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

2.2. import org.eclipse.swt.widgets.Shell;import org.eclipse.swt.widgets.Shell;

3.3. public class HelloWorld {public class HelloWorld {

4.4. public static void main(String[] args) {public static void main(String[] args) {

5.5. Display display = new Display();Display display = new Display();

6.6. Shell shell = new Shell(display);Shell shell = new Shell(display);

7.7. shell.setText("Hello World");shell.setText("Hello World");

8.8. shell.setSize(250, 100);shell.setSize(250, 100);

9.9.

10.10. shell.open();shell.open();

11.11.

12.12. while (!shell.isDisposed()) {while (!shell.isDisposed()) {

13.13. if (!display.readAndDispatch()) {if (!display.readAndDispatch()) {

14.14. display.sleep();display.sleep();

15.15. }}

16.16. }}

17.17. display.dispose();display.dispose();

18.18. }}

19.19. }}

Page 10: SWT TUTORIAL

Creating Widgets (Cont.)Creating Widgets (Cont.) Think of Think of Shell Shell object (line 6) being almost the same as a JFrame in object (line 6) being almost the same as a JFrame in

Swing, i.e. the highest-level container, which contains other widgets (e.g. Swing, i.e. the highest-level container, which contains other widgets (e.g. buttons, labels etc.) inside of itbuttons, labels etc.) inside of it

Unlike SwingUnlike Swing1.1. You need to create You need to create Display Display object (line 5), which represents the object (line 5), which represents the

underlying windowing system. This in turn serves as a parent to the underlying windowing system. This in turn serves as a parent to the Shell. Shell. (In SWT, every widget you create will always have its parent (In SWT, every widget you create will always have its parent passed into the widget’s constructor.)passed into the widget’s constructor.)

2.2. You need to keep the Shell open to listen for events with a while loop You need to keep the Shell open to listen for events with a while loop (lines 12-16). Otherwise, the Shell will immediately close itself.(lines 12-16). Otherwise, the Shell will immediately close itself.

3.3. Since you are not just writing some Java code (having the luxury of Since you are not just writing some Java code (having the luxury of garbage collector clean up after you), but are actually requesting some garbage collector clean up after you), but are actually requesting some heavyweight resources from the underlying platform – you need to heavyweight resources from the underlying platform – you need to dispose of those resources when you are done with them(line 17). dispose of those resources when you are done with them(line 17). (Luckily, disposing of the parent disposes of its child, so 99% of time you (Luckily, disposing of the parent disposes of its child, so 99% of time you will not be running around disposing of widgets right and left.)will not be running around disposing of widgets right and left.)

If you are a Swing guy, and the above 3 things greatly bother you – you If you are a Swing guy, and the above 3 things greatly bother you – you can write a simple SWTUtil class to help you deal with it …can write a simple SWTUtil class to help you deal with it …

Page 11: SWT TUTORIAL

Homegrown SWT UtilityHomegrown SWT Utility

SWTUtil.javaSWTUtil.java

import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

public class SWTUtil {public class SWTUtil { private static Display display = new Display();private static Display display = new Display();

public static Shell getShell() {public static Shell getShell() { Shell shell = new Shell(display);Shell shell = new Shell(display); return shell;return shell; }}

public static void openShell(Shell shell) {public static void openShell(Shell shell) { shell.open();shell.open();

// This loop keeps the shell open constantly listening for events // This loop keeps the shell open constantly listening for events while (!shell.isDisposed()) {while (!shell.isDisposed()) {

if (!display.readAndDispatch()) {if (!display.readAndDispatch()) { display.sleep();display.sleep(); }}

}} display.dispose();display.dispose(); }}}}

Page 12: SWT TUTORIAL

SWT Utility in ActionSWT Utility in Action

““Simplest SWT program” Simplest SWT program” rewritten using SWTUtil classrewritten using SWTUtil class

import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

public class HelloWorld {public class HelloWorld {

public static void main(String[] args) {public static void main(String[] args) {

Shell shell = Shell shell = SWTUtil.getShell();SWTUtil.getShell();

shell.setText(“Still Hello shell.setText(“Still Hello World");World");

shell.setSize(250, 100);shell.setSize(250, 100);

SWTUtil.openShell(shell);SWTUtil.openShell(shell);

}}

}}

Page 13: SWT TUTORIAL

Widget creation explainedWidget creation explained A widget in SWT is created byA widget in SWT is created by

1.1. Specifying parentSpecifying parent

2.2. Specifying styleSpecifying style A parent is the container that the widget is created inside of (e.g. Shell).A parent is the container that the widget is created inside of (e.g. Shell). Style is any constant from the SWT class (SWT.PUSH, SWT.BORDER, SWT.LEFT etc).Style is any constant from the SWT class (SWT.PUSH, SWT.BORDER, SWT.LEFT etc). All styles applicable to the widget can be found in the Javadoc for that widget (as well as its superclasses if any).All styles applicable to the widget can be found in the Javadoc for that widget (as well as its superclasses if any). If more than one style is desired – separate them out with a “|” bitwise operator (e.g. SWT.MULTI | SWT.V_SCROLL|SWT.H_SCROLL| If more than one style is desired – separate them out with a “|” bitwise operator (e.g. SWT.MULTI | SWT.V_SCROLL|SWT.H_SCROLL|

SWT.BORDER creates a multiline textarea that has vertical and horizontal scrollbars and a border around it). If no specific style is desired SWT.BORDER creates a multiline textarea that has vertical and horizontal scrollbars and a border around it). If no specific style is desired – use SWT.NONE. The style you are requesting is only a hint, so if the underlying platform doesn’t support it – you are out of luck.– use SWT.NONE. The style you are requesting is only a hint, so if the underlying platform doesn’t support it – you are out of luck.

Creating LabelCreating Label

Label (Composite parent, int style)Label (Composite parent, int style)

Creating ButtonCreating Button Button(Composite parent, int style)Button(Composite parent, int style)

Page 14: SWT TUTORIAL

LabelLabel Unselectable, uneditable textUnselectable, uneditable text SWT.VERTICAL or SWT.HORIZONTAL can be used together with SWT.SEPARATOR SWT.VERTICAL or SWT.HORIZONTAL can be used together with SWT.SEPARATOR

to create a label that is a horizontal/vertical separatorto create a label that is a horizontal/vertical separator LabelWorld.javaLabelWorld.java

1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;

2.2. import org.eclipse.swt.layout.GridLayout;import org.eclipse.swt.layout.GridLayout;

3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class LabelWorld {public class LabelWorld {

5.5. public static void main(String[] args) {public static void main(String[] args) {

6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();

7.7. shell.setText("Label World");shell.setText("Label World");

8.8. shell.setLayout(new GridLayout()); // layouts are explained later shell.setLayout(new GridLayout()); // layouts are explained later

9.9.

10.10. // Create labels// Create labels

11.11. new Label(shell, SWT.NONE).setText("Regular label");new Label(shell, SWT.NONE).setText("Regular label");

12.12. new Label(shell, SWT.SEPARATOR);new Label(shell, SWT.SEPARATOR);

13.13. new Label(shell, SWT.SEPARATOR|SWT.HORIZONTAL);new Label(shell, SWT.SEPARATOR|SWT.HORIZONTAL);

14.14.

15.15. // pack and show// pack and show

16.16. shell.pack();shell.pack();

17.17. SWTUtil.openShell(shell);SWTUtil.openShell(shell);

18.18. }}

19.19. }}

Page 15: SWT TUTORIAL

ButtonButton

Once a button – always a button. All types of buttons are created using the Button class. Once a button – always a button. All types of buttons are created using the Button class. Push buttons, radio buttons, check buttons, toggle buttons and even flat buttons.Push buttons, radio buttons, check buttons, toggle buttons and even flat buttons.

ButtonWorld.javaButtonWorld.java

1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.GridLayout;import org.eclipse.swt.layout.GridLayout;3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class ButtonWorld {public class ButtonWorld {5.5. public static void main(String[] args) {public static void main(String[] args) {6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();7.7. shell.setText("Button World");shell.setText("Button World");8.8. shell.setLayout(new GridLayout(2, true)); // layouts are explained later shell.setLayout(new GridLayout(2, true)); // layouts are explained later 9.9.

10.10. new Button(shell, SWT.PUSH | SWT.FLAT).setText("Flat Push Button");new Button(shell, SWT.PUSH | SWT.FLAT).setText("Flat Push Button");11.11. new Button(shell, SWT.CHECK).setText("Check Button");new Button(shell, SWT.CHECK).setText("Check Button");12.12. new Button(shell, SWT.TOGGLE).setText("Toggle Button");new Button(shell, SWT.TOGGLE).setText("Toggle Button");13.13. new Button(shell, SWT.RADIO).setText("Radio Button");new Button(shell, SWT.RADIO).setText("Radio Button");14.14.

15.15. // pack and show// pack and show16.16. shell.pack();shell.pack();17.17. SWTUtil.openShell(shell);SWTUtil.openShell(shell);18.18. }}19.19. }}

Page 16: SWT TUTORIAL

TextText Different types of text widgets are created using Text class by providing the appropriate stylesDifferent types of text widgets are created using Text class by providing the appropriate styles

TextWorld.javaTextWorld.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.GridLayout;import org.eclipse.swt.layout.GridLayout;3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class TextWorld {public class TextWorld {5.5. public static void main(String[] args) {public static void main(String[] args) {6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();7.7. shell.setText("Text World");shell.setText("Text World");8.8. shell.setLayout(new GridLayout()); // layouts are explained later shell.setLayout(new GridLayout()); // layouts are explained later 9.9.

10.10. new Text(shell, SWT.NONE).setText("Missing something ...");new Text(shell, SWT.NONE).setText("Missing something ...");11.11. new Text(shell, SWT.BORDER); // regular textfieldnew Text(shell, SWT.BORDER); // regular textfield12.12. new Text(shell, SWT.PASSWORD | SWT.BORDER).setText("password");new Text(shell, SWT.PASSWORD | SWT.BORDER).setText("password");13.13. new Text(shell, SWT.READ_ONLY | SWT.BORDER).setText("Can't type inside");new Text(shell, SWT.READ_ONLY | SWT.BORDER).setText("Can't type inside");14.14. new Text(shell, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP new Text(shell, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP 15.15. | SWT.BORDER).setText("\n\n\n");| SWT.BORDER).setText("\n\n\n");16.16.

17.17. // pack and show// pack and show18.18. shell.pack();shell.pack();19.19. SWTUtil.openShell(shell);SWTUtil.openShell(shell);20.20. }}21.21. }}

Page 17: SWT TUTORIAL

ListList Pick from a list – single or multiple selection availablePick from a list – single or multiple selection available

ListWorld.javaListWorld.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.GridLayout;import org.eclipse.swt.layout.GridLayout;3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class ListWorld {public class ListWorld {5.5. public static void main(String[] args) {public static void main(String[] args) {6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();7.7. shell.setText("List World");shell.setText("List World");8.8. shell.setLayout(new GridLayout(2, true)); // layouts are explained later shell.setLayout(new GridLayout(2, true)); // layouts are explained later 9.9.

10.10. String[] items = "One Two Three Four Five Six".split(" ");String[] items = "One Two Three Four Five Six".split(" ");11.11. List one = new List(shell, SWT.SINGLE | SWT.BORDER);List one = new List(shell, SWT.SINGLE | SWT.BORDER);12.12. one.setItems(items);one.setItems(items);13.13. one.select(2);one.select(2);14.14. List two = new List(shell, SWT.MULTI | SWT.BORDER);List two = new List(shell, SWT.MULTI | SWT.BORDER);15.15. two.setItems(items);two.setItems(items);16.16. two.setSelection(items);two.setSelection(items);17.17.

18.18. // pack and show// pack and show19.19. shell.pack();shell.pack();20.20. SWTUtil.openShell(shell);SWTUtil.openShell(shell);21.21. }}22.22. }}

Page 18: SWT TUTORIAL

ComboCombo Benefits of both Text and List widgets in one!Benefits of both Text and List widgets in one!

ComboWorld.javaComboWorld.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.GridLayout;import org.eclipse.swt.layout.GridLayout;3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class ComboWorld {public class ComboWorld {5.5. public static void main(String[] args) {public static void main(String[] args) {6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();7.7. shell.setText("Combo World");shell.setText("Combo World");8.8. shell.setLayout(new GridLayout(3, true)); // layouts are explained later shell.setLayout(new GridLayout(3, true)); // layouts are explained later 9.9.

10.10. String[] items = "One Two Three Four Five Six".split(" ");String[] items = "One Two Three Four Five Six".split(" ");11.11. Combo one = new Combo(shell, SWT.DROP_DOWN);Combo one = new Combo(shell, SWT.DROP_DOWN);12.12. one.setItems(items);one.setItems(items);13.13. Combo two = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY);Combo two = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY);14.14. two.setItems(items);two.setItems(items);15.15. Combo three = new Combo(shell, SWT.SIMPLE);Combo three = new Combo(shell, SWT.SIMPLE);16.16. three.setItems(items);three.setItems(items);17.17.

18.18. // pack and show// pack and show19.19. shell.pack();shell.pack();20.20. SWTUtil.openShell(shell);SWTUtil.openShell(shell);21.21. }}22.22. }}

Page 19: SWT TUTORIAL

GroupGroup Used to group widgets together. (Very similar to JPanel in Swing)Used to group widgets together. (Very similar to JPanel in Swing)

GroupWorld.javaGroupWorld.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.GridLayout;import org.eclipse.swt.layout.GridLayout;3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class GroupWorld {public class GroupWorld {5.5. public static void main(String[] args) {public static void main(String[] args) {6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();7.7. shell.setText("Group World");shell.setText("Group World");8.8. shell.setLayout(new GridLayout()); // layouts are explained later shell.setLayout(new GridLayout()); // layouts are explained later 9.9.

10.10. Group buttonGroup = new Group(shell, SWT.SHADOW_OUT);Group buttonGroup = new Group(shell, SWT.SHADOW_OUT);11.11. buttonGroup.setText("Six buttons");buttonGroup.setText("Six buttons");12.12. buttonGroup.setLayout(new GridLayout(3, true));buttonGroup.setLayout(new GridLayout(3, true));13.13. for(int i = 0; i < 6; i++) {for(int i = 0; i < 6; i++) {14.14. new Button(buttonGroup, SWT.RADIO).setText("Bottle " + (i + 1));new Button(buttonGroup, SWT.RADIO).setText("Bottle " + (i + 1));15.15. }}16.16.

17.17. // pack and show// pack and show18.18. shell.pack();shell.pack();19.19. SWTUtil.openShell(shell);SWTUtil.openShell(shell);20.20. }}21.21. }}

Page 20: SWT TUTORIAL

BrowserBrowser One of the newer widgets of SWT for displaying web content.One of the newer widgets of SWT for displaying web content. Cool stuff!!! (See the sample application later)Cool stuff!!! (See the sample application later)

BrowserWorld.javaBrowserWorld.java

1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.browser.Browser;import org.eclipse.swt.browser.Browser;3.3. import org.eclipse.swt.layout.FillLayout;import org.eclipse.swt.layout.FillLayout;4.4. import org.eclipse.swt.widgets.Shell;import org.eclipse.swt.widgets.Shell;

5.5. public class BrowserWorld {public class BrowserWorld {6.6. public static void main(String[] args) {public static void main(String[] args) {7.7. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();8.8. shell.setText("Browser World");shell.setText("Browser World");9.9. shell.setLayout(new FillLayout());shell.setLayout(new FillLayout());10.10.

11.11. Browser browser = new Browser(shell, SWT.BORDER);Browser browser = new Browser(shell, SWT.BORDER);12.12. browser.setSize(900, 500);browser.setSize(900, 500);13.13. browser.setUrl("http://www.eclipse.org/swt/");browser.setUrl("http://www.eclipse.org/swt/");14.14.

15.15. // pack and show// pack and show16.16. shell.pack();shell.pack();17.17. SWTUtil.openShell(shell);SWTUtil.openShell(shell);18.18. }}19.19. }}

Page 21: SWT TUTORIAL

Browser in ActionBrowser in Action

Page 22: SWT TUTORIAL

SWT LayoutsSWT Layouts

Layouts first introduced in AWTLayouts first introduced in AWT Ease burden of laying out componentsEase burden of laying out components Promote cross-platform GUI designPromote cross-platform GUI design

SWT offers 5 layouts:SWT offers 5 layouts:1.1. FillLayoutFillLayout

2.2. RowLayoutRowLayout

3.3. StackLayoutStackLayout

4.4. GridLayoutGridLayout

5.5. FormLayoutFormLayout

You set the composite’s layout by calling setLayout()You set the composite’s layout by calling setLayout() You don’t have to use a layout, but do you really want your widgets to You don’t have to use a layout, but do you really want your widgets to

disappear when the user resizes the window?disappear when the user resizes the window? More on layouts More on layouts http://www.eclipse.org/articles/Understanding%20Layouts/Understanding%20Layouts.htmhttp://www.eclipse.org/articles/Understanding%20Layouts/Understanding%20Layouts.htm

Page 23: SWT TUTORIAL

FillLayoutFillLayout Places all widgets in either a single column or a single row depending on if Places all widgets in either a single column or a single row depending on if

SWT.VERTICAL or SWT.HORIZONTAL is usedSWT.VERTICAL or SWT.HORIZONTAL is used Makes all widgets the same sizeMakes all widgets the same size

FillLayoutExample.javaFillLayoutExample.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.FillLayout;import org.eclipse.swt.layout.FillLayout;3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class FillLayoutExample {public class FillLayoutExample {5.5. public static void main(String[] args) {public static void main(String[] args) {6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();7.7. shell.setText("FillLayoutExample");shell.setText("FillLayoutExample");8.8. shell.setLayout(new FillLayout(SWT.HORIZONTAL));shell.setLayout(new FillLayout(SWT.HORIZONTAL));9.9.

10.10. for(int i = 0; i < 3; i ++) {for(int i = 0; i < 3; i ++) {11.11. new Button(shell, (i % 2 == 0) ? SWT.RADIO : SWT.PUSH).setText("Button " + i);new Button(shell, (i % 2 == 0) ? SWT.RADIO : SWT.PUSH).setText("Button " + i);12.12. new Text(shell, SWT.BORDER).setText("same size");new Text(shell, SWT.BORDER).setText("same size");13.13. }}14.14.

15.15. // pack and show// pack and show16.16. shell.pack();shell.pack();17.17. SWTUtil.openShell(shell);SWTUtil.openShell(shell);18.18. }}19.19. }}

Page 24: SWT TUTORIAL

RowLayoutRowLayout Similar to Similar to FillLayout FillLayout -- places all widgets in either a single column or a single row depending on if places all widgets in either a single column or a single row depending on if

SWT.VERTICAL or SWT.HORIZONTAL is usedSWT.VERTICAL or SWT.HORIZONTAL is used Doesn’t force all widgets to be the same sizeDoesn’t force all widgets to be the same size Can wrap to a new row or column if it runs out of spaceCan wrap to a new row or column if it runs out of space Can use Can use RowData RowData objects to determine initial heights/widths for controlsobjects to determine initial heights/widths for controls

RowLayoutExample.javaRowLayoutExample.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.RowData;import org.eclipse.swt.layout.RowData;3.3. import org.eclipse.swt.layout.RowLayout;import org.eclipse.swt.layout.RowLayout;4.4. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

5.5. public class RowLayoutExample {public class RowLayoutExample {6.6. public static void main(String[] args) {public static void main(String[] args) {7.7. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();8.8. shell.setText("RowLayoutExample");shell.setText("RowLayoutExample");9.9. shell.setLayout(new RowLayout(SWT.HORIZONTAL));shell.setLayout(new RowLayout(SWT.HORIZONTAL));10.10.

11.11. for(int i = 0; i < 3; i ++) {for(int i = 0; i < 3; i ++) {12.12. new Button(shell, (i % 2 == 0) ? SWT.RADIO : SWT.PUSH).setText("Button " + i);new Button(shell, (i % 2 == 0) ? SWT.RADIO : SWT.PUSH).setText("Button " + i);13.13. new Text(shell, SWT.BORDER).setLayoutData(new RowData(5, 50));new Text(shell, SWT.BORDER).setLayoutData(new RowData(5, 50));14.14. }}15.15.

16.16. // pack and show// pack and show17.17. shell.pack();shell.pack();18.18. SWTUtil.openShell(shell);SWTUtil.openShell(shell);19.19. }}20.20. }}

Page 25: SWT TUTORIAL

StackLayoutStackLayout Similar to Similar to CardLayoutCardLayout in Swing. The basic idea is that all widgets are stacked on top of each other and you can in Swing. The basic idea is that all widgets are stacked on top of each other and you can

only see one at a time.only see one at a time. Need to set Need to set topControl topControl attribute for the layout to show any widget on topattribute for the layout to show any widget on top Need to call Need to call layout()layout() on the Composite every time you reassign on the Composite every time you reassign topControltopControl

StackLayoutExample.javaStackLayoutExample.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.custom.StackLayout;import org.eclipse.swt.custom.StackLayout;3.3. import org.eclipse.swt.events.*;import org.eclipse.swt.events.*;4.4. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

5.5. public class StackLayoutExample {public class StackLayoutExample {6.6. public static void main(String[] args) {public static void main(String[] args) {7.7. final Shell shell = SWTUtil.getShell();final Shell shell = SWTUtil.getShell();8.8. shell.setText("RowLayoutExample");shell.setText("RowLayoutExample");9.9. shell.setLayout(new StackLayout());shell.setLayout(new StackLayout());10.10.

11.11. final Button button1 = new Button(shell, SWT.PUSH);final Button button1 = new Button(shell, SWT.PUSH);12.12. button1.setText("Button One");button1.setText("Button One");13.13. final Button button2 = new Button(shell, SWT.PUSH);final Button button2 = new Button(shell, SWT.PUSH);14.14. button2.setText("Button Two");button2.setText("Button Two");

15.15. class StackLayoutAdapter extends SelectionAdapter {class StackLayoutAdapter extends SelectionAdapter {16.16. public void widgetSelected(SelectionEvent event) {public void widgetSelected(SelectionEvent event) {17.17. ((StackLayout)shell.getLayout()).topControl = ((StackLayout)shell.getLayout()).topControl = 18.18. (event.widget == button1) ? button2 : button1;(event.widget == button1) ? button2 : button1;19.19. shell.layout();shell.layout();20.20. }}21.21. }}22.22. button1.addSelectionListener(new StackLayoutAdapter());button1.addSelectionListener(new StackLayoutAdapter());23.23. button2.addSelectionListener(new StackLayoutAdapter());button2.addSelectionListener(new StackLayoutAdapter());24.24.

25.25. ((StackLayout)shell.getLayout()).topControl = button1;((StackLayout)shell.getLayout()).topControl = button1;26.26. shell.pack();shell.pack();27.27. SWTUtil.openShell(shell);SWTUtil.openShell(shell);28.28. }}29.29. }}

Page 26: SWT TUTORIAL

GridLayoutGridLayout

Lays out controls in a grid.Lays out controls in a grid. A lot of people love this powerful layout.A lot of people love this powerful layout. You can easily specify what you want to happen when the composite is You can easily specify what you want to happen when the composite is

resizedresized 6 attributes (defaults are preset):6 attributes (defaults are preset):

1.1. int horizontalSpacing – horizontal space in pixels between int horizontalSpacing – horizontal space in pixels between adjacent cellsadjacent cells

2.2. int verticalSpacing – vertical space in pixels between adjacent int verticalSpacing – vertical space in pixels between adjacent cellscells

3.3. boolean makeColumnsEqualWidth – forces all columns to be boolean makeColumnsEqualWidth – forces all columns to be same widthsame width

4.4. int marginWidth – margin in pixels along right and left edgesint marginWidth – margin in pixels along right and left edges5.5. int marginHeight – margin in pixels along top and bottom edgesint marginHeight – margin in pixels along top and bottom edges6.6. int numColumns – number of columns for the layout int numColumns – number of columns for the layout

GridLayout(int numColumns, boolean makeColumnsEqualWidth)GridLayout(int numColumns, boolean makeColumnsEqualWidth) Uses GridData objects to provide for better controlUses GridData objects to provide for better control Too many options to list …Too many options to list … Warning Warning for Swing programmers – DO NOT TRY TO REUSE GridData for Swing programmers – DO NOT TRY TO REUSE GridData

objectsobjects Instead, you need to create a new GridData object for every widget that Instead, you need to create a new GridData object for every widget that

needs non-default behaviorneeds non-default behavior

Page 27: SWT TUTORIAL

GridLayoutExample.javaGridLayoutExample.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.layout.*;import org.eclipse.swt.layout.*;3.3. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

4.4. public class GridLayoutExample {public class GridLayoutExample {5.5. public static void main(String[] args) {public static void main(String[] args) {6.6. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();7.7. shell.setText("GridLayoutExample");shell.setText("GridLayoutExample");8.8. shell.setLayout(new GridLayout(2, false)); // 2 columns, same widthshell.setLayout(new GridLayout(2, false)); // 2 columns, same width9.9.

10.10. // Username// Username11.11. new Label(shell, SWT.RIGHT).setText("Username:");new Label(shell, SWT.RIGHT).setText("Username:");12.12. Combo cmbUsername = new Combo(shell, SWT.DROP_DOWN);Combo cmbUsername = new Combo(shell, SWT.DROP_DOWN);13.13. cmbUsername.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));cmbUsername.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));14.14. cmbUsername.setItems(new String[]{"Howard", "Admin", "Kalman"});cmbUsername.setItems(new String[]{"Howard", "Admin", "Kalman"});15.15. cmbUsername.setText("Admin");cmbUsername.setText("Admin");16.16.

17.17. // Password// Password18.18. new Label(shell, SWT.RIGHT).setText("Password:");new Label(shell, SWT.RIGHT).setText("Password:");19.19. new Text(shell, SWT.BORDER | SWT.PASSWORD).GridData(GridData.FILL_HORIZONTAL));new Text(shell, SWT.BORDER | SWT.PASSWORD).GridData(GridData.FILL_HORIZONTAL));20.20.

21.21. // Login Button// Login Button22.22. Button loginButton = new Button(shell, SWT.PUSH | SWT.FLAT);Button loginButton = new Button(shell, SWT.PUSH | SWT.FLAT);23.23. loginButton.setText("Proceed to your account");loginButton.setText("Proceed to your account");24.24. GridData data = new GridData(GridData.FILL_HORIZONTAL);GridData data = new GridData(GridData.FILL_HORIZONTAL);25.25. data.horizontalSpan = 2; // span 2 columnsdata.horizontalSpan = 2; // span 2 columns26.26. loginButton.setLayoutData(data);loginButton.setLayoutData(data);

27.27. shell.pack();shell.pack();28.28. SWTUtil.openShell(shell);SWTUtil.openShell(shell);29.29. }}30.30. }}

Page 28: SWT TUTORIAL

FormLayoutFormLayout

Considered the most complex layout of SWTConsidered the most complex layout of SWT Based on Based on y = ax + by = ax + b (not that most people who use it care) (not that most people who use it care) MAXIMUM flexibilityMAXIMUM flexibility People who understand it – love it People who understand it – love it The basic idea is that you layout the widgets relative to each other or to the enclosing The basic idea is that you layout the widgets relative to each other or to the enclosing

compositecomposite Needs a tutorial of its own and is therefore not covered here …Needs a tutorial of its own and is therefore not covered here …

Page 29: SWT TUTORIAL

Event HandlingEvent Handling If you are familiar with Swing – this last part should be a joke.If you are familiar with Swing – this last part should be a joke. SWT widgets can SWT widgets can listen listen for events to happen.for events to happen. If you would like to hear when and what they hear – you need to If you would like to hear when and what they hear – you need to attach a listener attach a listener to to

the widgetthe widget Listener Listener is basically an interface that defines when certain behaviors happenis basically an interface that defines when certain behaviors happen Sometimes, listener tries listening out for two many things, but you only care to listen Sometimes, listener tries listening out for two many things, but you only care to listen

for one particular eventfor one particular event In such a case – you need an In such a case – you need an adapter. Adapteradapter. Adapter is a class that is a class that implements implements the the

interface and from which you can just extend and override the method you are interface and from which you can just extend and override the method you are interested in.interested in.

Some of the popular Some of the popular listeners/adapterslisteners/adapters are listed below are listed below FocusListener/FocusAdapterFocusListener/FocusAdapter – listens for focus gained and focus lost events – listens for focus gained and focus lost events KeyListener/KeyAdapterKeyListener/KeyAdapter – listens for key releases and key presses – listens for key releases and key presses ModifyListenerModifyListener(only has 1 method) – listens for text modifications(only has 1 method) – listens for text modifications VerifyListenerVerifyListener – listens for (and potentially intercepts) text modifications – listens for (and potentially intercepts) text modifications MouseListener/MouseAdapterMouseListener/MouseAdapter – listens for mouse button presses – listens for mouse button presses SelectionListener/SelectionAdapterSelectionListener/SelectionAdapter – listens for selection events (similar to – listens for selection events (similar to

ActionListener in Swing) ActionListener in Swing)

Page 30: SWT TUTORIAL

EventHandling.javaEventHandling.java1.1. import org.eclipse.swt.SWT;import org.eclipse.swt.SWT;2.2. import org.eclipse.swt.events.*;import org.eclipse.swt.events.*;3.3. import org.eclipse.swt.layout.*;import org.eclipse.swt.layout.*;4.4. import org.eclipse.swt.widgets.*;import org.eclipse.swt.widgets.*;

5.5. public class EventHandling {public class EventHandling {6.6. private static boolean numbersOnly;private static boolean numbersOnly;7.7. public static void main(String[] args) {public static void main(String[] args) {8.8. Shell shell = SWTUtil.getShell();Shell shell = SWTUtil.getShell();9.9. shell.setText("EventHandling");shell.setText("EventHandling");10.10. shell.setLayout(new GridLayout(2, false)); shell.setLayout(new GridLayout(2, false)); 11.11. 12.12. // input// input13.13. Label lblInput = new Label(shell, SWT.RIGHT);Label lblInput = new Label(shell, SWT.RIGHT);14.14. lblInput.setText("Type in here:");lblInput.setText("Type in here:");15.15. GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END);GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END);16.16. lblInput.setLayoutData(data);lblInput.setLayoutData(data);17.17. Text input = new Text(shell, SWT.BORDER);Text input = new Text(shell, SWT.BORDER);18.18. input.addVerifyListener(new VerifyListener() {input.addVerifyListener(new VerifyListener() {19.19. public void verifyText(VerifyEvent vEvent) {public void verifyText(VerifyEvent vEvent) {20.20. vEvent.doit = false; // don't allow anything but numbersvEvent.doit = false; // don't allow anything but numbers21.21. if(!numbersOnly || vEvent.character == '\b') {if(!numbersOnly || vEvent.character == '\b') {22.22. vEvent.doit = true;vEvent.doit = true;23.23. }}24.24. else if(Character.isDigit(vEvent.character) && numbersOnly) {else if(Character.isDigit(vEvent.character) && numbersOnly) {25.25. vEvent.doit = true;vEvent.doit = true;26.26. }}27.27. }}28.28. });});

Page 31: SWT TUTORIAL

EventHandling.javaEventHandling.java

29.29. Button btnAllow = new Button(shell, SWT.CHECK);Button btnAllow = new Button(shell, SWT.CHECK);

30.30. btnAllow.setText("Allow numbers only");btnAllow.setText("Allow numbers only");

31.31. data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);

32.32. data.horizontalSpan = 2;data.horizontalSpan = 2;

33.33. btnAllow.setLayoutData(data);btnAllow.setLayoutData(data);

34.34. btnAllow.addSelectionListener(new SelectionAdapter() {btnAllow.addSelectionListener(new SelectionAdapter() {

35.35. public void widgetSelected(SelectionEvent selectionEvent) {public void widgetSelected(SelectionEvent selectionEvent) {

36.36. numbersOnly = ((Button)(selectionEvent.widget)).getSelection();numbersOnly = ((Button)(selectionEvent.widget)).getSelection();

37.37. }}

38.38. });});

39.39. shell.pack();shell.pack();

40.40. SWTUtil.openShell(shell);SWTUtil.openShell(shell);

41.41. }}

42.42. }}

Page 32: SWT TUTORIAL

syncExec() / asyncExec()syncExec() / asyncExec() You should only be updating user interfaces from the user interface thread.You should only be updating user interfaces from the user interface thread. For example, say you create a Label in your main thread. Then, you have a separate thread that For example, say you create a Label in your main thread. Then, you have a separate thread that

does some sort of a long computation. Then, you want to update your label with the result of the does some sort of a long computation. Then, you want to update your label with the result of the second thread’s computation. You second thread’s computation. You CANNOTCANNOT just call label.setText(newValue) in your second thread. just call label.setText(newValue) in your second thread.

Instead, you have to call either syncExec(Runnable) or asyncExec(Runnable) methods on the Instead, you have to call either syncExec(Runnable) or asyncExec(Runnable) methods on the instance of Displayinstance of Display

// Say you run a thread that calculates new time approximately every second// Say you run a thread that calculates new time approximately every second // and tries to update a label // and tries to update a label new Thread(new Runnable() {new Thread(new Runnable() {

public void run() {public void run() { Display display = shell.getDisplay();Display display = shell.getDisplay(); while(!shell.isDisposed()) {while(!shell.isDisposed()) { try {try { display.asyncExec(new Runnable() {display.asyncExec(new Runnable() { public void run() {public void run() {

clock.setText((new Date()).toString());clock.setText((new Date()).toString()); }} });}); Thread.sleep(1000);Thread.sleep(1000); } } catch (InterruptedException e) {catch (InterruptedException e) { e.printStackTrace();e.printStackTrace(); }}

}} }} }).start();}).start();

Page 33: SWT TUTORIAL

Sample ApplicationSample Application

Goal: Write a cute browser in SWT (under Goal: Write a cute browser in SWT (under 300 lines) that handles most HTML300 lines) that handles most HTML

CuteBrowser.java uses SWTUtil.javaCuteBrowser.java uses SWTUtil.java Run the application on Windows XP Run the application on Windows XP

computer that has java installedcomputer that has java installed