SWT: A powerful competitors of AWT and SWING

zhaozj2021-02-11  225

SWT: A powerful competitors of AWT and SWING

content:

First SWT program

Analysis SWT API

More complex procedures

System resource management

Thread problem

SWT extension: jface

Reference

About author

Also in The Java Zone:

teaching

Tools & products

Code and components

All articles

Practical skills

Ni Dapeng (ndp@e2one.com)

February 2003

Since the birth of Java, it has been successful in too many fields, but it rarely emerges in the graphical interface program.

. For the reason, Java language default graphical interface development package AWT and swings are really difficult to get rid of, regardless of speed and outside

Views, they are difficult to accept. Today, the SWT development package prepared by Eclipse organizes A.

A better choice other than WT and Swing. In this article, SWT is simple but as comprehensive as possible.

Java language prestige and its achievements in desktop applications (GUI programs) are obviously unable to match, still very

I can see a very successful Java desktop program. Although there are large software such as JBuilder, NetBean, JProbe as a representative

But this still can't prove that Java's GUI program is successful: their appearance is always with other in the same operating system platform.

Software looks grid. The demand for machine configuration seems to be never end, which makes them only have some to have some

The current highest performance PC's programmers are tolerated, or those who don't care about money and time. Be

Most computer users speaking, AWT or SWING represents a weird interface and unacceptable speed. Standard W

IDGET Toolkit (SWT) may be the end of Java's nightmare, the majority of Java programmers can finally develop high

The efficiency GUI program, they have standard appearance, almost no one can see your program is written in Java, more

It is important that these programs are cross-platform.

The SWT itself is only a set of underlying graphical interface APIs written in the Eclipse IDE environment in order to develop the Eclipse IDE environment. or

Xu is unintentional, or intentionally, so far, SWT exceeds Sun Company, whether in performance and appearance.

AWT and SWING provided. At present, Eclipse IDE has been developed to version 2.1, SWT is already stable. Herein

Stability should include two layers:

First, the performance is stable, and the key is to stem from the design concept of SWT. SWT maximizes the graphical structure of the operating system

The API, that is, the SWT is just simple application JNI technology as long as the operating system provides the corresponding graphic components.

They only do not provide components in the operating system, and SWT will be analog implementation. Can see SWT

Performance stability depends on the stability of the corresponding operating system graphics components.

Another stability refers to the class in the SWT API package, the name and structure of the method have changed less, and the programmer does not have to worry

Eclipse has developed very fast (Eclipse IDE has a Nightly version released every day), but

The program code changes too much. Update from a version of SWT to another, usually just need to change the SWT package

Yes.

First SWT program

Let's start a SWT program. (Note: The following examples and instructions are mainly for Windows platforms, others

The operating system should be similar to the same size). The first thing to find a SWT package in the Eclipse installation file, and the Eclipse organization does not provide

Separate SWT packages, you must download the full Eclipse development environment to get a SWT package. SWT is open as an Eclipse

A plug-in form of the environment exists, you can at $ {your Eclipse installation path} / plugins path

The directory is searching for the SWT.jar file, which contains all the Java class files in SWT in the found JAR file. Because SWT should

Used JNI technology, so it is also necessary to find a corresponding JNI localized library file, due to the difference between the version and the operation platform.

The name of the localization library file will have some differences, such as SWT-Win32-2116.dll is the Eclipse bu under the Window platform.

The dynamic library of ILD 2116, and the extension of the corresponding version of the library file in the UNIX platform should be .so, and so on. pay attention to

Eclipse is an open source project, so you can also find SWT source code in these directories.

This will help development.

Below is a code that opens the empty window (only the main method).

Import com.e2one.example;

Public class openshell {

Public static void main (String [] args) {

Display display = new display () and DISPLAY ();

Shell shell = new shell (display);

shell.open ();

// Start the event processing loop until the user closes the window

While (! shell.isdisposed ()) {

IF (! display.readDispatch ())

Display.sleep ();

}

Display.dispose ();

}

}

Confident in the ClassPath included SWT.jar files, use the Javac to compile examples. After compiling, you can run JAV.

A -DJAVA.LIBRARY.PATH = $ {你 你 s 本 文件 文件}} com.e2one.example.openshell

For example, the path where the SWT-Win32-2116.dll is the path is C: / swtlib, and the command running should be java -djava.l

ibrary.path = c: / swtlib com.e2one.example.openshell. After successful operation, the system will open a

Empty window.

Analysis SWT API

Let us further analyze the composition of the SWT API. All SWT classes use org.eclipse.swt as a prefixed prefix

Here, in order to simplify the description, we use the * to represent org.eclipse.swt, such as * .widgets package, representative

Org.eclipse.swt.widgets package.

Our most commonly used graphics components are basically included in the * .widgets package, such as Button, Combo, Text, Labe

l, sash, table, and more. Two of these most important components are both shell and composite. Shell is equivalent to the application

The main window frame of the order, the above example code is to open an empty window in the application shell component. Composite

The Panel object in swing acts as the role of the component container, when we want to add some components in a window

It is best to use Composite as a container of other components, then go to * .Layout package to find a suitable layout

formula. SWT has a combination of layout and layout data in Swing or AWT in SWT, in * .layo

Four Layout can be found in the UT package and the layout structure object corresponding to them. At * .custo

In the M bag, it contains the extension of some basic graphics components, such as Clabel there, is the standard Label component.

Extended, you can add text and pictures at the same time, or you can add bits. StyleDtext is an extension of the Text component, it

Provides a wealth of textual features, such as the background color, foreground or font settings for a paragraph. At * .custom package

A new STACKLAYOUT layout method can also be found.

SWT responds to user operations, such as mouse or keyboard events, and Observer mode in AWT and SWING.

In the * .event package, you can find the Listener interface of the event and the corresponding event object, such as common mouse events.

Monitor Interface MouseListener, MouseMovelistener, and MouseTrackListener, and the corresponding event object

Mouseevent.

* .Graphics package can find APIs for pictures, cursors, fonts, or drawings. For example, can be used through the Image class.

Unlike different types of picture files. Drawing functionality of the picture, component or display is implemented via the GC class.

For different platforms, Eclipse has also developed some targeted APIs. For example, in the Windows platform, you can pass *

.ole.win32 package is easy to call the OLE control, so that the Java program is embedded in IE browser or Word, Excel.

Fight!

To learn more about SWT, you can find the Javadoc description of the SWT in the Help document of the Eclipse IDE. of course

The most in-depth understanding of the source code of SWT, this is also the charm of the programmer!

More complex procedures

Let us show a more complex program than the above example. This program has a text box and a press

Key, when the user clicks on the button, the text box displays a welcome information.

For text boxes and buttons have a relatively reasonable size and layout, a gradlayout layout is used. This layout

It is the most commonly used in SWT and the most powerful layout, almost all formats may be reached by gradlayout. under

The program also involves how to apply system resources (color), and how to release system resources.

PRIVATE VOID INITSHELL (shell shell) {

/ / Set the layout object for the shell

GridLayout gshelllay = new gridlayout ();

Shell.setLayout (gshelllay);

/ / Construct a container for a Composite component as a text box and a button

Composite Panel = New Composite (shell, swt.none);

/ / Specify a layout structure object for Panel. Let Panel as much as possible, all

The space for the application window.

GridData gpaneldata = new griddata (GridData.grab_horizontal | griddata.g

RAB_VERTICAL | GridData.fill_both;

Panel.setLayOutdata (gpaneldata);

/ / Set a layout object for Panel. Text boxes and buttons will be displayed in this layout object.

GridLayout gpanellay = new gridlayout ();

Panel.setLayout (gpanellay);

/ / Generate a background color for Panel

Final Color Bkcolor = New Color (Display.getCurrent (), 200, 0,200);

Panel.setBackground; BKColor

/ / Generate text box

Final text text = new text (panel, swt.multi | swt.wrap);

/ / Specify a layout structure object for the text box, where the text box is as much as possible with the space of Panel.

GridData gtextdata = new griddata (griddata.grab_horizontal | griddata.grab_vertage | griddata.fill_both;

Text.setLayOutdata (gtextdata);

/ / Build button

Button Butt = New Button (Panel, SWT.PUSH);

Butt.Settext ("Push");

/ / Specify the mouse event for the button

Butt.addmouselistener (new mouseadapter () {

Public void mousedown (MouseEvent E) {

// Show information when the user clicks the button

Text.Settext ("Hello Swt");

}

});

// The Disposelistener is triggered when the main window is turned off. Here is used to release the background color of the Panel.

Shell.adddisposelistener (new disposelistener () {

Public void widgetdisposed (DisposeEvent E) {

Bkcolor.dispose ();

}

});

}

Join the method INITSHELL () in this code to the first example of opening an empty window, getting a successful success

Run a full GUI application. The operation method can refer to the first example.

System resource management

Developing programs in a graphical operating system to call resources in the system, such as pictures, fonts, colors, and more.

Usually these resources are limited, the programmer must be very careful: when it is no longer used,

Please release it as soon as possible, or the operating system will end sooner, you have to restart, and more serious will lead to system crash.

.

SWT is developed by Java, a great advantage of Java language itself is JVM's "garbage collection mechanism", programmers are usually not

The release of the restriction variable, the recovery of memory. So, for SWT, the operation of system resources is nothing

? The answer is a bad news, a good news.

The bad news is that the SWT does not use the JVM garbage collection mechanism to deal with the resource recovery problem of the operating system, a key cause

It is because the JVM garbage collection mechanism is uncontrollable, that is, the programmer can't know, it is impossible to do it in some

Always let JVM recycle resources! This is fatal on the processing of system resources. Imagine your program hopes in a loop statement.

Go to see tens of thousands of pictures, the regular processing method is to transfer one, view, and then release the image resources.

, Then transfer to the next picture in the loop, this is for the operating system, only a picture occupied at any time.

resource of. But if this process is completely handed over to the JVM, maybe it will be released after the end of the loop statement.

Put the picture resources, the result may be that your program has not run yet, the operating system is over.

But the following good news may make this bad news becomes irrelevant. For SWT, just understand two simple "gold

"The rule can be assured to use system resources! The reason why the gold definition is called the gold, one is because few, only two, the second is because

Surprise for them. The first one is "who occupies, who releases", the second is "the parent member is destroyed, the sub-component is also

It is destroyed. The first principle is a principle without any exception, as long as the program calls the constructor of the system resource class,

The program should be concerned to release this system resource at a moment. For example, call

Font Font = New Font (Display, "Courier", 10, SWT.NORMAL); then call when you do not need this font

Font.dispose ();

For the second principle, it means that if the program is called the Dispose () method of a component, then all the components of all this component

Parts will also be destroyed automatically to the dispose () method. The relationship between the sub-component and the parent member referred to herein is in the calling structure.

The constructor is formed. such as,

Shell shell = new shell ();

Composite Parent = New Composite (shell, swt.null);

Compositive child = new Composite (parent, swt.null);

Where Parent's parent member is shell, while shell is the main window of the program, so there is no corresponding parent member, at the same time

Parent also includes a Child sub-component. If you call the shell.dispose () method, apply the second rule, then PA

The Dispose () method of the Rent and Child components will also be automatically called by the SWT API, and they also destroy.

For these two rules, the articles in Reference 2 have a more in-depth introduction.

Thread problem

In the GUI system of any operating platform, all access operations of the component or some graphics API are strictly synchronized and serialized.

. For example, the buttons in a graphical interface can be set to an enabled or disabled (disable).

Normal processing method is that users have to be placed in an event handling queue to the GUI system to the button status setting operation (this

It means that the access operation is serialized) and then processes (this means that the access operation is synchronized). Imagine when button

When the setting function of the state has not yet been completed, the program wants to set the button to disable the status.

Cause conflict. In fact, this operation will trigger an exception in any GUI system.

The Java language itself provides a multi-threaded mechanism. This mechanism is unfavorable to the GUI programming. It cannot guarantee the graphic structure.

Synchronization and serialization of the pieces. SWT uses a simple and straightforward way to adapt to the local GUI system to thread

Seeking: In SWT, there is usually a unique thread called "user thread", which can only be called in this thread.

Access operation of components or certain graphics APIs. If the program directly calls these access operations directly in the non-user thread, then S

WTEXCepiton will be thrown. But SWT also provides two ways in the * .widget.display class.

The access operation of the graphics component in non-user threads, this is syncexec (runnable) and asyncexe

C (runnable) These two methods are implemented. E.g:

/ / This time the program runs in a non-user thread and wants to join a button on the component panel.

Display.getCurrent (). AsyncExec (New Runnable () {

Public void run () {

Button Butt = New Button (Panel, SWT.PUSH);

Butt.Settext ("Push");

}

});

Methods Syncexec () and asyncexec () are differentiated that the former is returned after the specified thread is executed, and the latter

Then return to the current thread whenever the specified thread is executed.

SWT extension: jface

The relationship between JFACE and SWT is better than the relationship between Microsoft's MFC and SDK, JFACE is based on SWT development, and its API is more than SWT.

Adding to use, but the function is not SWT directly. For example, the following code Apply the MessageDialog in the JFACE Opens a Warning dialog:

MessageDialog.Openwarning (Parent, "Warning", "Warning Message");

If you only complete the above features with SWT, the statement will not be less than 30 lines!

The JFACE is originally a set of APIs written for more convenient use of SWT, which is the main purpose to develop Eclipse IDE.

Environment, not to apply to other independent applications. Therefore, it is difficult to put JFA before the Eclipse 2.1 version.

The CE API is completely peeled out from the Eclipse's kernel API, always introduces less ECE ECE.

The CLIPSE core code class or interface can get a JFACE development package without any compilation errors. But current Eclipse

Organization seems to have gradually realized that JFACE's important role in developing independent applications, in development of 2.1

In the version, JFACE has also begun to become a completely independent development package as SWT, but this development package is still in fluctuations.

(When the author writes this, the Eclipse2.1m3 version of the application). The package prefix of the JFACE development package is org.eclipse.jfa

CE starts. JAR package and source code are also the same as SWT, as well as $ {your Eclipse installation path} / plugins

Find.

For developers, when developing a graphics component, a better way is to find a first to JFACE packages.

Is there a more concise implementation method, if you don't use the SWT package to achieve it. For example, JFACE is provided for the dialog

Very good support, in addition to various types of dialogs (such as the messagedialog used above, or pair with Title columns

Box), if you want to implement a custom dialog, it is best to inherit from the Dialog class in JFACE, not from SWT.

* .widget.dialog inherited.

Applying the classes in the Preference package in JFACE easy to make your own software a very professional configuration dialog. Correct

For TREE, TABLE and other graphical components, they also need to be associated with data while displaying, such as data displayed in TABLE.

In the VIEW package in JFACE, the programming method of model-view is provided for such components, which makes display

Data is separated, more developed and maintained. The most features in JFACE are the processing of text content. allowable

Dozens of text processing related classes are found in org.eclipse.jface.ec.eclipse.jface.text. * Packages.

More coming with the app

The Java program is usually published in the way in the Class file, running the Class requires JRE or JDK support. This is Java

Another fatal weakness of the GUI program, imagined to make an app for the users, no matter what your program

There are more simple features, or your code is very streamlined, you have to let users download a 7, 8M JRE, then

What is a frustrating thing. Moreover, Class usually means exposure to source code, anti-compilation

Tools make those people who are tuned to get your source code. Although there are many encryption methods for Class, but that is always

At the expense of sacrificial performance. Fortunately, there are other ways available: compile the class into an EXE file!

Reference 3 provides a detailed approach to applying GCJ to compile SWT into an EXE file. As a supplement to that article,

Currently, you can also get GCJ under Windows by downloading Cygwin. Excelsior is also a very useful.

Good compiler, the only regret is its price!

The advantages of this Java language itself through the SWT development kit, simple, cross-platform, reliable, etc. are gradually fused to graphics

Interface application development. Therefore, I believe that the door of another success in the Java language is gradually opening. Reference:

Http://www.e2one.com Extreme Software Studio Application SWT & JFACE API Developed Enterprise Real Time Communication IM Software

It is an example of the SWT & JFACE development of the Standalone program.

Http://www.eclipse.org/articles/swt-design-2/swt-design-2.html This article details

How should SWT developers manage system resources.

http://www-900.ibm.com/developerWorks/cn/linux/guitoolkit/j-nativegui/index.sh

TML describes how to apply the SWT program to the GCJ compile cost of the machine application file.

Http://www-900.ibm.com/developerWorks/cn/java/l-eclipse/index.shtml introduced ECLI

The use of PSE and a simple plugin development process.

Www.eclipse.org All about Eclipse, SWT, JFACE can find the answer here. Also

A website with an Eclipse development environment.

Http://www.cygwin.com/ You can get the Windows version of GCJ.

About author

Ni Dapeng, has many years of software development experience, of which the time in the past four years is concentrated in Java related technologies. Can

E-mail: ndp@e2one.com contact him.

转载请注明原文地址:https://www.9cbs.com/read-5031.html

New Post(0)