SWT programming with Eclipse
1. Why use SWT?
SWT is IBM developed a cross-platform GUI development framework. Why is IBM to create another GUI? Why don't you use the existing Java GUI framework? To answer these questions, I need to go back to the early age of Java.
Sun has created a set of cross-platform GUI frames AWT (Abstract Windowing Toolkit). This AWT framework uses local window components (Native Widgets) but it exists in an LCD problem. This LCD problem caused its loss of major platform characteristics. In other words, if the platform A has a window component 1-40 and the platform B has window components 20-25, this cross-platform AWT framework can only provide the intersection of these two sets.
In order to solve this problem, Sun creates a new framework to use an analog window component (Emulated Widgets) instead of the local window component (Native Widgets). This method solves the LCD problem while providing a wealth of window components, but other problems have also been produced. For example, the Swing application is no longer consistent with the local program. Although JVM has great improvements, Swing applications still have performance issues that their local pairing do not have. Moreover, the Swing application consumes too much memory, so it is not suitable for small devices such as PDA and mobile phones.
IBM discovers that these methods cannot meet their needs. Therefore, IBM creates a new GUI library called SWT, which solves the problems in the AWT and SWING frameworks. The SWT framework uses JNI to access the local window component (Native Widget), if a window component cannot be obtained on the host platform, then SWT will simulate this unacceptable window component.
2. Basic materials for a SWT application
Display, shell and widgets are the basic materials for a SWT application. Displays is used to manage event loops and communication between the UI threads and other threads. The shell is a form that is managed by the operating system Form Manager in the application. Any SWT application requires at least one Display instance and 1 or more shell instances.
Figure 1. SWT program in different perspectives
Figure 1 illustrates different views of an SWT application. The first picture is a simplified UI object inload map. The second figure is a structure of the UI object. The third picture is the created UI.
If an application uses multiple threads, each thread uses its own Display object instance. Then you can get the current active Display object instance by using a static display.getcurent () method.
A shell represents a window in a special operating system. A shell can maximize, normalize, and minimize. There are two types of shells. One is created by top-level shell as the main window of Display, and the other is the conversation shell of other shells.
The type of shell is determined by the Style bit that passes the SHELL constructor. The default value of the shell is the SHELL of the conversation. That is, if any value is not delivered to the constructor parameters, then created the default conversation shell. If an Display object is used as a parameter, it is a top-level shell.
Some window components (Widget) must be set when creating. These window components (Widget) attributes are called STYLE BITS. Style Bits is a constant defined in the SWT class. Such as Button Button = New Button (shell,
Developing a SWT application is different from the development of a Swing application. In order to start development of a SWT application, you need to add the SWT library to the classpath while setting the necessary environment variables.
The first required library is a SWT.jar file, which is located at the eclipse_home / eclipse.swt.win32_2.1.0 / ws / win32 directory. Depending on the Eclipse version you use, you may need to use different directories. This swt.jar file must be added to your classpath, to this to Project-> PropRares-> add variable -> eclipse home -> extend, select the SWT.jar library according to the path, and then click OK.
Then, you can compile the SWT application, but because the runtime is thrown, it cannot be run because SWT.jar uses a local library. You need to set up a java.library.path environment variable to use a local library in Java.
Console Output
java.lang.UnsatisfiedLinkError: no swt-win32-2133 in java.library.pathat java.lang.ClassLoader.loadLibrary (ClassLoader.java:1403) at java.lang.Runtime.loadLibrary0 (Runtime.java:788) at java. Lang.system.loadLibrary (System.java: 832) ... at Org.eclipse.swt.widgets.display.
To set a java.library.path variable, to Run-> Run ...-> java applicaton-> new -> arguments -> vm arguments. Then, how to modify the PATH as follows, paste it into the VM Arguments section. -Djava.library.path = c: /eclipse/plugins/org.eclipse.swt.win32_
2.1.0
/ OS / WIN32 / X86
Loading a local library
If you need to load any local libraries used by the application, you can use the runtime.getplatform.loadLibrary ("libraryname") method.
Complete these steps, you can run the SWT program in your Eclipse environment.
4. Your first SWT application
Creating a typical SWT application requires the steps:
Create a DISPLAY
Create one or more shells
Set the layout manager
Create widgets in the shell
Open the shell window
Write an event forwarding loop
Destroy Display
You can quickly run the code snippet in this article using the code template below. You can copy the paste these code to the appropriate area. Such as source code 1: Source code 1. SWT application template
Import Org.eclipse.swt.Layout.RowLayout;
Import org.eclipse.swt.widgets.display;
Import org.eclipse.swt.widgets.shell;
Public Class SlideXample
{
Public static void main (string args [])
{
Display display = new display () and DISPLAY ();
Shell shell = new shell (display);
Shell.setLayout (New RowLayout ());
// ------------------------
// Your code comes to here.
// ------------------------
Shell.pack ();
shell.open ();
While (! shell.isdisposed ())
{
IF (! display.readDispatch ())
Display.sleep ();
}
Display.dispose ();
}
}
This example shows an empty window. You can add Widget to the template on the top. Any SWT application needs
A Display and one or more
Shells. This shell is a synthetic object; it can accommodate other synthetic objects. If there is no shell set
Layout, widget plus shell is not seen. The shell window must
Open to display.
Event processing loops read and forwards the GUI event. If there is no event processing loop application window that cannot be displayed. Open the shell window even by an Open () method. After letting it, you need to destroy when shell is discarded.
DISPLAY.
Import the required library
You can use the Source-> Organize IMPORTS menu or Ctrl Shift O from moving into the required library.
5. Run the SWT application outside Eclipse
To run the SWT application without using the Eclipse, the SWT.JAR library must be in the classpath and the java.library.path environment variable must be set correctly. According to the host platform, there must be a right local inventory. For the Windows platform, you can complete the configuration of the local library according to the following:
Put SWT.DLL under the same folder as the program.
Place SWT.DLL under the java_home / bin / folder.
Place SWT.DLL under the C: / Windows / System32 folder.
Javac-ClassPath C: /swt/swt.jar HelloWorld.javajava-ClassPath C: /swt/swt.jar ;. -djava.library.path = C: / SWT HelloWorldJava.library.path is the necessary environment variables necessary for JNI. If you don't set this environment variable. Your DLL class cannot be accessed. In this case, the application cannot run normally and will throw an exception.
SWT library
SWT inventory is in the Plug-in directory of Eclipse. If you want to get a SWT library without downloading the entire Eclipse package, you can download this SWT library separately in http://www.eclipse.org/downloads.
6. SWT package (Packages)
SWT is mainly composed of the following packages. The definition of these packages is obtained from Eclipse's API documentation. You can get the entire API document on the Eclipse website. Org.eclipse.swt: The class that defines the constants and exceptions that are required to use. This package consists of three classes: SWT, SWTEXCEPTION and SWTERROR. The SWT class may be the most popular class because it contains constants such as keyboards, errors, colors, layouts, text style, buttons. Org.eclipse.swt.widgets: Most core SWT window components include supported interfaces and classes. Org.eclipse.swt.events: Defines the Typed Events, Listeners, and Events used by the SWT component. This package has three sets of different classes: Listener interface, Adapter class, and EVENT class. Org.eclipse.swt.dnd: Contains classes that are supported by Drag-and-DROPs in SWT Window Components. Org.eclipse.swt.layout: The class contains automatic settings and size controls for SWT window components. Org.eclipse.swt.print: The class contains a profile supporting the SWT window component. Org.eclipse.swt.graphics: This package provides a class, rectangular, region, color, cursor, font, image context (GC), etc. required for basic drawing operations, and contains display image code and load / save them. The image class of the public API. 7. Dialog
The implementation of the dialog is local. That is, the dialog box is the platform component as the window assembly. The Dialogs of SWT is inherited from Dialog abstraction. The dialog is not a window component but he can hold the window component.
Figure 2. Dialog class level map.
SWT has different types of dialogs. Some dialogs have special properties. The Dialog class can be used in source code 2.
Source code 2. Messagebox example
Messagebox messagebox =
New MessageBox (Shell, Swt.ok | SWT.CANCEL);
IF (MessageBox.Open () == SWT.OK)
{
System.out.println ("OK Is Pressed.");
}
The OPEN () method of each dialog returns a different type. For example, the MessageBox dialog returns the int type from the Open () method. Therefore, there is a need to write different conditions to handle the return value of each dialog.
ColorDialog displays a color selection palette. It returns a RGB object from the return method.
DirectoryDialog allows you to select a directory. It returns a string from the Open () method. The return value is the selected directory. Of course, additional filters can be set to filter some directory.
FontDialog enables users to select a font from all fonts. It returns a fontdata object from the Open () method.
FileDialog enables users to select a file. Alternatively, the extension filter, path filter, and filename filter can be set. The dialog is as shown in Table 1:
Table 1. SWT dialog STYLE BIT constant
SWT.Open
Shows Open button in the dialog
SWT.SAVE
Shows Save Button in The Dialog
PrintDialog Use the user to select a printer before printing. It returns a PrinterData object from the Open () method.
MessageBox is used to give user feedback information. You can use or (|) to do different styles, such as the source code 3:
Source code 3. Messagebox example
Messagebox messagebox =
New MessageBox (shell,
SWT.OK |
SWT.CANCEL |
SWT.ICON_WARNING);
MessageBox.setMessage ("www.korayguclu.de");
Messagebox.open ();
Figure 3 is the running message box of the upper side example.
Figure 3. MessageBox dialog
The available button constants are listed below. Make or operate the combination of different buttons. The SWT framework creates a dialog box according to Style Bits. Button constants are: SWT.Abort, SWT.OK, SWT.CANCEL, SWT.RETRY, SWT.IGNORE, SWT.YES and SWT.NO.
Table 2 shows the icons that the dialog can be used.
Table 2. SWT icon Style bit constant
SWT.ICON_ERROR
SWT.ICON_INFORMATION
SWT.ICON_QUESTION
SWT.ICON_WARNING
SWT.ICON_WORKING
8. Widgets
The SWT GUI object is inherited from Widget and Control class. The Widget object is a general method for the base class to define the GUI class. The CONTROL class is the base class of all window GUI classes is to say that the components inherited from the Control class require a window or dialog box to display.
The MENU object also requires a window to display, but this demand is indirectly satisfied. A Menu object requires a Control object.
Figure 4. Widget class level map
Figure 4 shows the class level map of the Widget. Widget, Item, Scrollbar and Control class are abstract classes.
8.1. Widget event
Widget event summary Table 3. Simplification, only the event name is included in the table. We can easily use the name of the event class using
Table 3. SWT EVENTS
Event name
Window assembly
Generated time
ARM
Menuitem
A menu item is highlighted
CONTROL
Control, TableColumn, Tracker
A control is changed or moving
Dispose
Widget
When the window component is destroyed
FOCUS
CONTROL
When a control gets or loses focus
Help
Control, Menu, MenuItem
When users need help (for example, press F1)
Key
CONTROL
When the control gets the keyboard focus and a button is pressed or released
Menu
Menu
Menu display or hide
Modify
Combo, Text
The text of the window component is modified
Mouse
CONTROL
When the mouse is pressed, released or double-clicked in the control range
Mousemove
CONTROL
Mouse over the control
MouseTrack
CONTROL
The mouse is entered, leaving or hovering above the control.
Paint
CONTROL
The control needs to be redrawn
SELECTION
Button, Combo, CoolItem, List, Menuitem, Sash, Scale, Scrollbar, Slider, Styledtext, Tabfolder, Table, TableColumn, Tabletree, Text, ToolItem, Tree
An Item is selected in the control
Shell
Shell
The shell is minimized, maximized, activated, passivated, or close to TRAVERSE
CONTROL
When the control is traversed (tabbed)
Tree
Tree, TableTree
A Tree Item is contracted or expanded
Verify
Text, Styledtext
The text of the window component will be modified
8.2. Useful window components
Figure 5. Control class level map
All Control classes can have a border. You can use the SWT.Border constant to add a border to the control class.
SWT STYLE constant
It is generally required to indicate style constants. If you don't know which constant or you don't want to indicate it, you can use SWT.NULL.
8.2.1
Button
The button can have different styles. The style of the button is determined by the Style bit. Table 4 shows the button list and their styles constants.
Table 4. SWT button Style Bit constant and example
constant
example
description
SWT.Arrow
A button is used to display the pop-up dialog. The direction of the arrow is determined by the alignment constant.
SWT.CHECK
The selection box can be an image.
SWT.PUSH
A button
SWT.RADIO
Single selection button that can be used in Group
SWT.Toggle
Similar to SWT.PUSH, but it can hold the state until the second click.
8.2.2
Slider, Scaler (Scale) and ProgressBar window assembly
Scale (scale) represents a selection of continuous values. The range can be set with the SCALE class's setMinimum () and setmaximum () methods. And you can use the getSelection () method to get the selected value. The ruler has only one selected value at a time. That is, there is no possibility.
Figure 6. Slider and ruler with together
Depending on the parameter value passed to the constructor, we can create different slits and rules. Slider and ruler constant shown in Table 5:
Table 5. Style constant of the SWT slider and ruler
SWT.HORIZONTALSWT.VERTICAL
Display horizontal or vertical components
Feel free, you can use the SWT.Border constant to create a border around the ruler. This constant has no effect on the slider.
Source 4. Slider Widget EXAMPLE
Final Slider Slider = New Slider (Shell, SWT.Vertical);
Slider.setminimum (0);
Slider.setmaximum (100);
Slider.setIncrement (5);
Slider.SetPageIncrement (10);
Slider.setSelection (25);
Slider.addseelectriStener
New selectionAdapter ()
{
Public void WidgetSelected (SelectionEvent E)
{
System.out.println ("Selection:" Slider.getSelection ());
}
}
);
The progress bar assembly is similar to the slider and the ruler component, but it cannot be selected. It is used to show the progress of a task. You can use the Swt.Smooth and Swt.Interminate constant for your progress bar components.
8.2.3
Text window components
A text window component can be used to display or edit text. In addition, you can use the StyleDText window component to display text with different fonts and colors. The StyleDText window component allows for setting the foreground, background color, and fonts of the specified range text block.
Figure 7. Text window components
We can create a Text window component using the constants listed in Table 6. Therefore, SWT.H_Scroll and SWT.V_Scroll constants can be used to increase the scroll bar for the Text window component.
Table 6. SWT text style bit constant swt.multiswt.single
Show a single line or multi-line window components
SWT.READ_ONLY
Create a read-only component
SWT.Wrap
Text automatic wrap
Source code 5 is a simple example of using the Text component.
Source 5. Text Widget EXAMPLE
TEXT TEXT =
NEW text (shell, swt.multi | swt.wrap);
8.2.4
List (list) window component
List window components can be used to display a list of optional string. In the case of choice, the List object will send an event to Listener. This type of selection can be radio, or multiple choices can be made. The selected type is determined by Swt.single and SWT.Multi constant. The List window component is a scrollable component. Therefore, SWT.H_Scroll and SWT.V_Scroll constants can be used to increase the scroll bar to the Text window component.
Figure 8. List window assembly
The code snippet below shows a simple List window component.
Source 6. List Example
Final List List = New List (Shell, SWT.MULTI);
For (int i = 1; i <11; i )
{
List.add (i ".) www.korayguclu.de");
}
List.addSelectrionListener
New selectionAdapter ()
{
Public void WidgetSelected (SelectionEvent E)
{
List list = (list) E.GETSOURCE ();
String [] str = list.getSelection;
For (int i = 0; i { System.out.println ("Selection:" STR [I]); } } } ); 8.2.5 Box assembly The window frame assembly can be used to display a combined window assembly in a variable area. The following figure is a window frame component example. Figure 9. Window frame assembly Next is an example of a basic window frame component: Source 7. Sash Example Button button = new button (shell, swt.push); Sash Sash = New Sash (Shell, SWT.Vertical); Button button1 = new button (shell, swt.push); 8.3. Combination Window Components Composite Widgets Combined window components can accommodate other combination window components. The Composite class is the parent class that combines window components. Figure 10. Composite can accommodate other combinations The combination class can accommodate other combinations. This accommodating relationship is built with a constructor of a combined window component class. SWT has no add () method compared to SWING; instead, you must use constructor to establish a tolerance relationship. As seen in Figure 10, the shell class is also a combination class. That is to say, the shell object can accommodate other combined classes. The combination class can be rolled, that is, swT.h_scroll and swt.v_scroll constant can be added to the combined window assembly to add a scroll bar. 8.3.1 . Table window components Table window components can display a batch of string items or images. Compared with other combination window components, you cannot add combined controls to the Table window component. The sub-component of the Table window component must be TableItem type. Figure 11. Table window assembly Constants in Table 7 can be used for Table window components Table 7. SWT TABLE STYLE BIT SWT.MULTITISWT.SINGLE Enable single or multiple options SWT.FULL_SELECTION Enable SWT.CHECK Start in each line display a selection box The code snippet in the source code 8 indicates how the use of two columns of Table components Source code 8. Table window components example Final Table Table = New table (shell, swt.single); TableColumn col1 = New TableColumn (Table, SWT.LEFT); Col1.settext ("Coloumn 1"); Col1.SetWidth (80); TableColumn col2 = New TableColumn (Table, SWT.LEFT); Col2.Settext ("Coloumn 2"); Col2.SetWidth (80); TableItem item1 = new TableItem (Table, 0); Item1.Settext (new string [] {"a", "b"}); TableItem item2 = new TableItem (Table, 0); Item2.Settext (New String [] {"a", "b"}); Table.setHeadervisible (TRUE); Table.SetLinesVisible (TRUE); 8.3.2 COMBO (Composite Box) Window Components The Combo window component allows the user to select a value from the list of values or enter a new value casually. Combination box (Combo) is similar to a list assembly, but uses a limited space. Although the combination frame is combined, it is meaningless to increase the child elements. Its element must be a String type. One element can be added to the combo box using the Add (String Element) method defined in the COMBO class. Figure 12. Combination frames of different styles The SWT constant below can be used for Combo window components: Table 8. SWT Combo Style Bit Constants SWT.DROP_DOWN Drop-pull combination box SWT.READ_ONLY Read-only combination box SWT.SIMPLE Simple combo box (non-pull-down combination). Figure 11 The example below illustrates the use of Combo components: Source 9. Combo EXAMPLE Final Combo Combo = New Combo (Shell, SWT.DROP_DOWN); For (int i = 1; i <11; i ) { Combo.add (i ".) ELEMENT"); } Combo.Settext ("text"); Combo.addseelectrionListener New selectionAdapter () { Public void WidgetSelected (SelectionEvent E) { System.out.println ("Selection:" Combo.getText ()); } } ); 8.3.3 Tree window components The Tree window component depicts the selection hierarchy of the tree in the tree. Although the TREE class is combined, it cannot add a combined class object to it. The child of the TREE class must be the ThreeItem type. Figure 13. Tree window components of different styles The table below is a list of Tree component constants. Table 9. SWT Tree Style Bit Constant SWT.SINGLESWT.MULTI Allow radio or multiple choices SWT.CHECK The start displaying a selection box at each node. The lower side is a simple TREE component example. Source code 10. Tree example Final Tree = New tree (shell, swt.single); For (int i = 1; i <11; i ) { Final TreeItem Item1 = New TreeItem (Tree, SWT.NULL); Item1.Settext ("Node" i); For (int J = 1; j <6; j ) { Final TreeItem Item11 = New TreeItem (item1, swt.null); Item11.Settext ("Node" i "." J); } } Tree.AddSelectronListener New selectionAdapter () { Public void WidgetSelected (SelectionEvent E) { System.out.println ("Selection:" Tree.getSelection () [0]); } } ); 8.3.4 TabFolder TabFolder components allow users to select a page from some pages. Although it is combined, it cannot add other combination window components. Components plus TabFolder must be a TabItem type. The content of Tab can be set using TabItem's setControl (Control Control) method. Figure 14. TabFolder window assembly A simple TabFolder example: Source code 11. TabFolder example Final TabFolder TabFolder = New TabFolder (Shell, Swt.Border); For (int i = 1; i <5; i ) { // Create a TabItem TabItem item = New TabItem (TabFolder, Swt.null); Item.Settext ("TabItem" i); // Create a Control Label label = New label (Tabfolder, SWT.BORDER); Label.Settext ("Page" i); // Add a control to the TabItem Item.setControl (label); } 8.3.5 Coolbar window components The Coolbar window component provides an area that can add items on dynamic placing spaces. You can add one or more Toolbar components to Coolbar. A Coolbar can accommodate one or more COOLITEMs. Although it is a combination window assembly, you cannot add other combinations to it. The child of Coolbar must be a COOLITEM type. Figure 15. CoolBar window assembly Examples used by the Coolbar window component: Source 12. Coolbar Example Coolbar coolbar = New Coolbar (Shell, Swt.Border); Coolbar.setlayOutdata ( New filllayout ()); // Create a Tool Bar Which IT // THE control of the coolitem For (int K = 1; k <3; k ) { Toolbar Toolbar = New Toolbar (Coolbar, SWT.FLAT); For (int i = 1; i <5; i ) { TOOLITEM ITEM = New ToolItem (Toolbar, Swt.null); Item.Settext ("B" K "." i); } // Add a coolitem to a coolbar COOLITEM COOLITEM = New CoolItem (Coolbar, Swt.null); // set the control of the coolitem COOLITEM.SETCONTROL (TOOLBAR); // you have to specify the size Point size = Toolbar.computesize (SWT.DEFAULT, SWT.DEFAULT); Point Coolsize = COOLITEM.COMPUTESIZE (size.x, size.y); COOLITEM.SETSIZE (COOLSIZE); } 8.4. Overview of child controls Some controls receive sub-components as child. For example, a combination component accepts a combined component. Some components only need items such as Item (item) as follows: Table 10. Items of components Window assembly item description Coolbar CoolItem The item is optional, dynamically placed on the area of Coolbar. Menu Menuitem The item is the choice under the menu. TabFolder TabItem Item is Tab in TabFolder TABLE TableItemTableColumn The item is the row in the table. Toolbar ToolItem The item is the button on the toolbar. Tree TreeItem The item is the node on the tree. in conclusion SWT is the core part of the Eclipse user interface. The Eclipse platform is based on the SWT library. To expand your SWT knowledge, you can download the SWT example on the SWT website.