Java Desktop Application Design: SWT Introduction

Source: Internet
Author: User
Tags ole

The reputation of Java is obviously very different from what it has achieved in desktop applications (GUI programs). So far, it is rare to see very successful Java Desktop programs. Although there are large software such as JBuilder, netbean, and Jprobe, this still cannot prove that the Java GUI program is successful: their appearance is always incompatible with other software on the same operating system platform. There seems to be endless demands for machine configuration, which can only be tolerated by programmers who always have the highest-performance PC, or those who don't care about money and time. For most computer users, AWT or swing represents a weird interface and an unacceptable speed. Standard Widget Toolkit (SWT) may be the terminator of Java's nightmare. Java programmers can finally develop highly efficient GUI programs with a standard appearance, almost no one can see that your program is written in Java. More importantly, these programs are cross-platform.

SWT itself is only a set of underlying GUI APIs compiled by eclipse to develop the Eclipse IDE environment. It may be unintentional or intentional. So far, SWT has surpassed AWT and swing provided by Sun in terms of performance and appearance. Currently, Eclipse IDE has been developed to version 2.1, and SWT is very stable. The stability here should contain two meanings:

First, it refers to the stability of performance. The key is the design concept of SWT. SWT maximizes the image component API of the operating system. That is to say, as long as the operating system provides the corresponding image components, SWT simply uses the JNI technology to call them, only those components that are not provided in the operating system can SWT perform a simulation on its own. It can be seen that the stability of SWT performance mostly depends on the stability of the graphic components of the corresponding operating system.

The other stability means that the name and structure of classes and methods in the swt api package have rarely changed, programmers don't have to worry about the rapid development progress of eclipse Organization (Eclipse IDE has a daily release of the nightly version), which leads to excessive changes in their program code. Update the SWT from one version to another. Generally, you only need to replace the SWT package.

The first SWT Program

Let's start a SWT program. (Note: The following examples and descriptions are mainly applicable to the Windows platform. Other operating systems should be similar ). First, find the SWT package in the eclipse installation file. The eclipse organization does not provide a separate SWT package to download. You must download the complete eclipse development environment to obtain the SWT package. SWT exists as a plug-in the eclipse development environment. You can search for SWT in many subdirectories under $ {Your eclipse installation path}/plugins path. JAR file. The JAR file found contains all the Java class files of SWT. Because SWT applies the JNI technology, it also needs to find the corresponding JNI localization library file. Due to the different versions and operating platforms, the name of the localization library file may be different, for example, the SWT-WIN32-2116.DLL is the dynamic library of eclipse build 2116 under the window platform, and the extension of the Library file in the corresponding version of the UNIX platform should be. so, and so on. Note that eclipse is an open-source project, so you can find the source code of SWT in these directories. I believe this will be very helpful for development. Below is a piece of code to open an empty window (only the main method ).

Import com. e2one. example;
Public class openshell {
Public static void main (string [] ARGs ){
Display display = New Display ();
Shell shell = new shell (Display );
Shell. open ();
// Start the event processing cycle until the user closes the window
While (! Shell. isdisposed ()){
If (! Display. readanddispatch ())
Display. Sleep ();
}
Display. Dispose ();
}
}

Make sure that the SWT. jar file is included in the classpath. Compile the example program with javac. After compilation, you can run Java-djava. library. path =$ {path of your SWT local library file} COM. e2one. example. openshell, for example, the path of the SWT-WIN32-2116.DLL is C:/swtlib, the command should be Java-djava. library. path = C:/swtlib COM. e2one. example. openshell. After the operation is successful, an empty window is opened.

Analyze SWT API

Next, let's further analyze the composition of SWT APIs. All SWT classes use Org. eclipse. SWT is the prefix of the package. to simplify the description, we use * to represent the prefix Org. eclipse. SWT, such *. the widgets package represents Org. eclipse. SWT. widgets package.

The most commonly used graphic components are basically included in the *. widgets package, such as button, combo, text, label, Sash, table, and so on. The two most important components are shell and composite. Shell is equivalent to the main window Framework of the application. In the code above, the application shell component opens an empty window. Composite is equivalent to a panel object in swing and acts as a component container. When we want to add some components to a window, we 'd better use composite as the container of other components and then go *. layout package to find a suitable layout method. SWT also uses the combination of layout and layout data in swing or AWT for component layout *. in the layout package, you can find four layout and the layout structure object corresponding to them (layout data ). In *. the m package contains extensions for some basic graphic components, such as clabel, which is an extension of the standard label component. text and images can be added at the same time, or border can be added. Styledtext is an extension of text components. It provides rich text functions, such as setting the background color, foreground color, or font of a text segment. You can also find a new stacklayout Layout Method in the *. Custom package.

SWT's response to user operations, such as mouse or Keyboard Events, also uses the observer mode in AWT and swing, in *. in the event package, you can find the listener interface for event listening and corresponding event objects, such as the commonly used mouse event listening interface mouselistener, mousemovelistener, mousetracklistener, and the corresponding event object mouseevent.

* The graphics package can find APIs for images, cursors, fonts, or plotting. For example, you can use the image class to call different types of image files in the system. The GC class is used to plot images, components, or displays.

For different platforms, eclipse also developed some targeted APIs. For example, on the Windows platform, you can easily call the ole control through the *. Ole. Win32 package, which makes it possible for Java programs to embed ie browsers or word, Excel and other programs!

More complex programs

The following shows a program that is more complex than the preceding example. This program has a text box and a button. When you click the button, the text box displays a welcome message.

The gradlayout layout method is used here to have a reasonable size and layout for text boxes and buttons. This layout is the most common and powerful Layout Method in SWT, and almost all formats can be achieved through gradlayout. The following program also involves how to apply system resources (color) and how to release system resources.

Private void initshell (shell ){
// Set the layout object for Shell
Gridlayout gshelllay = new gridlayout ();
Shell. setlayout (gshelllay );
// Construct a composite component as a container for text boxes and buttons
Composite Panel = new composite (shell, SWT. None );
// Specify a layout object for the panel.
Let the Panel be as full as possible with shell,
That is, the space of all application windows.
Griddata gpaneldata = new griddata (griddata. grab_horizontal | griddata. grab_vertical | griddata. fill_both );
Panel. setlayoutdata (gpaneldata );
// Set a layout object for the panel. The text box and buttons are displayed according to the layout object.
Gridlayout gpanellay = new gridlayout ();
Panel. setlayout (gpanellay );
// Generate a background color for the panel
Final color bkcolor = new color (display. getcurrent (), 200,0, 200 );
Panel. setbackground (bkcolor );
// Generate a text box
Final text = new text (panel, SWT. multi | SWT. Wrap );
// Specify a layout object for the text box,
Make the text box as full as possible as the Panel space.
Griddata gtextdata = new griddata (griddata. grab_horizontal | griddata. grab_vertical | griddata. fill_both );
Text. setlayoutdata (gtextdata );
// Generate buttons
Button butt = new button (panel, SWT. Push );
Butt. settext ("push ");
// Specify a mouse event for the button
Butt. addmouselistener (New mouseadapter (){
Public void mousedown (mouseevent e ){
// The information is displayed when you click the button.
Text. settext ("Hello SWT ");
}
});
// When the main window is closed, the disposelistener is triggered. This is used to release the background color of the Panel.
Shell. adddisposelistener (New disposelistener (){
Public void widgetdisposed (disposeevent e ){
Bkcolor. Dispose ();
}
});
}

Add the method initshell () in this code to the first example to open an empty window. A complete GUI application can be successfully run. For the running method, refer to the first example.
System Resource Management

In a graphical operating system, developers must call system resources, images, fonts, colors, and so on. These resources are usually limited, so programmers must be very careful when using them: release them as soon as possible, otherwise the operating system will soon run out of light, it has to be restarted, and even worse, the system will crash.
SWT is developed in Java. One of the major advantages of the Java language itself is the "garbage collection mechanism" of JVM. Programmers usually ignore issues such as variable release and memory collection. So for SWT, is the same for system resource operations? The answer is bad news and good news.

The bad news is that SWT does not adopt the JVM garbage collection mechanism to deal with the Resource Recycling problem of the operating system. A key factor is that the JVM garbage collection mechanism is uncontrollable, that is, programmers cannot know, it is impossible for the JVM to recycle resources at a certain time! The processing of system resources is fatal. Imagine that your program wants to view tens of thousands of images in a loop statement. The conventional processing method is to call one image and view it each time, then immediately release the image resource, and then call the next image in a loop. For the operating system, the program occupies only one image resource at any time. However, if this process is completely handled by the JVM, the JVM may release the image resources after the loop statement ends. the result may be that your program is not running yet, the operating system is down.

However, the following good news may make the bad news irrelevant. For SWT, you only need to understand two simple "golden" rules to use system resources with confidence! The reason is called the Golden Rule. One is because there are only two, and the other is because they are surprisingly simple. The first is "who occupies and who releases", the second is "the parent component is destroyed, and the child component is also destroyed ". The first principle is a principle without any exceptions. As long as the program calls the constructor of the system resource class, the program should be concerned with releasing the system resources at a certain time. For example

Font font = new font (display, "Courier", 10, SWT. Normal );

So it should be called when this font is not needed

Font. Dispose ();

The second principle is that if a program calls the dispose () method of a component, the child components of this component will be destroyed by the dispose () method automatically called. Generally, the relationship between the child component and the parent component is formed when the component constructor is called. For example,

Shell shell = new shell ();
Composite parent = new composite (shell, SWT. null );
Composite child = new composite (parent, SWT. null );

The parent component of parent is shell, while shell is the main window of the program. Therefore, there is no parent component, and parent also includes child components. If you call the shell. Dispose () method and apply the second rule, the dispose () Methods of the Parent and Child components will be automatically called by SWT APIs, and they will be destroyed accordingly.

Thread Problems

In the GUI system of any operating platform, access to components or some graphical APIs must be strictly synchronized and serialized. For example, a key component in a graphic interface can be set to an enable or disable. The normal processing method is, the user's button status setting operations must be put into the event processing queue of the GUI system (this means that the access operations are serialized) and then processed in sequence (this means that the access operations are synchronized ). Imagine that when the setting function of the available button status is not executed, the program will want to set this button to disabled, which will inevitably cause a conflict. In fact, this operation triggers exceptions in any GUI system.

The Java language itself provides a multi-threaded mechanism, which is unfavorable for GUI programming and cannot guarantee the synchronization and serialization of graphic component operations. SWT adopts a simple and direct method to adapt to the thread requirements of the local GUI system: in SWT, there is usually a unique thread called "User thread, only in this thread can access components or some graphical APIs be called. If the program directly calls these access operations in a non-user thread, the swtexcepiton exception will be thrown. But SWT is also in *. widget. the display class provides two methods to indirectly access graphical components in non-user threads. This is through syncexec (runnable) and asyncexec (runnable) these two methods are implemented. For example:

// At this time, the program runs in a non-user thread and you want to add a button on the component panel.

Display. getcurrent (). asyncexec (New runnable (){
Public void run (){
Button butt = new button (panel, SWT. Push );
Butt. settext ("push ");
}
});

The difference between syncexec () and asyncexec () is that the former must be returned after the execution of the specified thread ends, and the latter will immediately return to the current thread regardless of whether the specified thread is executed or not.

SWT Extension: jface

The relationship between jface and SWT is similar to the relationship between Microsoft's MFC and SDK. jface is developed based on SWT, and its API is easier to use than SWT, but its function is not direct to SWT. For example, the following code applies messagedialog in jface to open a warning dialog box:

Messagedialog. openwarning (parent, "warning", "warning message ");

If you only use SWT to complete the above functions, there will be no less than 30 lines of statements!

Jface was originally a set of APIS for more convenient use of SWT. Its main purpose is to develop the Eclipse IDE environment, rather than to apply it to other independent applications. Therefore, before eclipse 2.1, it is difficult to completely remove jface APIs from the eclipse kernel APIs, it is always necessary to import more or less eclipse core code classes or interfaces other than jface To Get A jface development kit without any compilation errors. However, at present, the eclipse organization seems to have gradually realized that jface plays an important role in developing independent applications. In version 2.1 under development, jface has also begun to become a complete and independent development kit like SWT, but this development kit is still being changed (the eclipse2.1m3 version applied when I wrote this article ). The prefix of the jface Development Kit starts with org. Eclipse. jface. The jar package and source code are the same as those of SWT, and you can find them at $ {Your eclipse installation path}/plugins path.

For developers, when developing a graphical component, it is better to go to The jface package to find out if there are more concise implementation methods, if you do not use the SWT package. For example, jface provides good support for the dialog box, except for various types of dialog boxes (such as messagedialog or a dialog box with the title column ), to implement a custom dialog box, you 'd better inherit from the dialog class in jface, instead of from * In SWT *. widget. dialog inheritance.

Classes in the preference package in the application jface can easily make a very professional configuration dialog box for their own software. For graphic components such as tree and table, they must also be associated with the data displayed, such as the data displayed in the table, the View package in jface provides a model-view programming method for such components. This method separates the display from the data, which is more conducive to development and maintenance. The most common function provided by jface is to process text content. You can find dozens of classes related to text processing in the org. Eclipse. jface. Text. * package.

Closer to the application

Java programs are usually published in the form of class files. Running a class requires support from JRE or JDK. This is another fatal weakness of the Java GUI program. Imagine that for a wide range of users, no matter how simple your program functions or your code is, you have to ask the user to download a JRE of 7 and 8 MB, which is so frustrating. In addition, for programmers, class usually means the exposure of source code, and The Decompilation tool allows those who are eager to get your source code easily. Although there are many encryption methods for the class, it is always at the cost of performance. Fortunately, there are other methods available: Compile the class into an EXE file!

Through the SWT Development Kit, the advantages of simple, cross-platform, reliable and other Java languages are gradually integrated into the application development of graphical interfaces. Therefore, I believe that another successful Java language is gradually opening.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.