Chapter 3 Section 3 Analysis of SWT Design Principles

Source: Internet
Author: User
Section 3 analyzes the SWT Design Principles

Returned directory

 

In the first chapter, we have introduced that SWT uses the local control library provided by the underlying operating system. It is only a Java interface for the interaction between the program and the underlying system. The lifecycle of a local control is like a mirror of a Java control object: When a Java Control is created, the local control is created at the same time; When a Java Control is destroyed, the local control is also destroyed. This design avoids a situation where the method of the code control is called before the underlying control is created ). This situation exists in other toolkit, which makes the lifecycle of the local control and the code control inconsistent [2].

For example, let's take a look at the two-step creation process of MFC (Microsoft Foundation classes. To create a button, the Code is as follows:

Cbutton button; // create a C ++ object on the stack

Button. Create (<parameters>); // create a window object

For example:

Cbutton button; // create a C ++ object on the stack

Cstring STR = _ T ("hi"); // create a cstring to record the text of the button

Button. setwindowtext (STR); // set the text of the button-Something went wrong

Button. Create (<parameters>); // create a window object

No error is reported during code compilation, but the runtime is different from the development. During debugging, assertion is triggered, and the behavior of the release version is undefined.

Control container [3]

Most GUI requirements indicate the container before creating a control. During the control's lifecycle, it belongs to [4] of that container. The lifecycle of a container determines the lifecycle of the control. In addition, many local controls have detailed features, that is, style, which must be set during creation. For example, a button can be a push button or a check box ). Because the local control corresponding to the SWT control needs to be created when building it, it must pass this information to its constructor ). The SWT control usually requires two parameters: a parent and a style ). A container is an org. Eclipse. SWT. Widgets. widget or its subclass. The optional type is an integer constant predefined in the SWT class ). A single style can be passed, or multiple styles can be merged with spaces or (OR. In this book, we will introduce the style of a control at the same time.

Destroy controls

Swing developers use the content in this section as evidence of low SWT and laugh at it. Generally, Java developers may feel uncomfortable or even annoying here, because the content in this section is: programmers should clear their own work. This concept has been abandoned by Java developers because it has put aside the Java garbage collection mechanism and regresses back to the situations that developers were responsible for a long time ago.

Why should I destroy objects? Java's garbage collection mechanism manages the memory well, but GUI resource management operates under many constraints. The number of available GUI resources is very limited, and on many platforms, it is the limit of the entire system. Because SWT works directly with the local underlying graphics resources, each SWT resource requires a GUI resource. Releasing resources in time not only improves the performance of the current SWT program, the performance of other running GUI programs is also prompted. Java's garbage collection mechanism has no time to guarantee, which may lead to poor management of graphics resources. Because of this, programmers must take responsibility for themselves.

How many tasks are there? In fact, it is not heavy at all. In a series of SWT articles, Carolyn MacLeod and Steve northover describe two simple rules [5]:

  • Who created and destroyed
  • Parent is dead and child is also dead [6]

Rule 1: Who created and destroyed

At the beginning of this chapter, we know that local resources will also be created when the SWT object is created. In other words, when the SWT object constructor is called, the underlying local resources are created. Assume that you have compiled the following code. You have constructed a SWT color object and allocated a color resource on the underlying GUI platform:

Color color = new color (display, 255, 0, 0); // create a red color

According to rule 1, you have created it, so you must destroy it after use, as shown below:

Color. Dispose (); // I created and destroyed

However, if you do not call the constructor to obtain a resource, you do not need to destroy the resource. For example, consider the following code:

Color color = display. getsystemcolor (SWT. color_red); // red

Again, you have a color object that can accommodate the red resources of the underlying platform, but it is not your application (allocate. According to rule 1, you should not destroy it. Why not? It does not belong to you-you borrowed it. Other objects may be used or will be used. Destroying such a resource can cause heavy losses.

Rule 2: The parent is dead, and the child is also dead.

To call dispose () for every SWT object created with new, it will soon become boring and may make SWT edge. Fortunately, SWT designers realized this and created a logic-level connection for automatic destruction [7]. When a container is destroyed, all its controls are also destroyed. This means that when a shell is destroyed, all its controls are also automatically destroyed. You will see that in the "Hello, world" program, although a label object is created using the constructor, label. Dispose () is never called (). When the user closes the shell, the label object is automatically destroyed.

You may think that you never need to call dispose (). This section is a waste of space. Indeed, in many programs you write, resources have containers, and they are automatically destroyed. Consider this situation: you want to change the font of the text control. Your code may be as follows:

Text text = new text (shell, SWT. Border); // create text

Font font = new font (display, "Arial", 14, SWT. Bold); // create a font

Text. setfont (font); // set the font

The font object you created does not have a container, so it will not be destroyed automatically, or even when the shell closes and the Text object that uses it is destroyed. You may feel that it is a burden to destroy the font, but you must realize that text has nothing to do with the destruction of font-it does not own font. In fact, you may apply a font object to multiple controls. Automatic destruction may cause serious consequences.

Ignore destroyed objects

Readers may have noticed a gap in the Image life cycle discussed in this chapter. In these cases, the Java object that encapsulates the local control is still in the effective range (is still in scope), but the shell object that it belongs to has been destroyed; or is the destruction function of a control manually called? Is the local control destroyed? When the underlying local control does not exist, can I call the function of this Java object?

This is indeed the case. If you call a function of a local control that has been destroyed, it will cause a lot of trouble. Once a control is destroyed, it should not do anything to it even if it is still within the valid range. Yes, this Java object is available, but the underlying peer has been destroyed. If you try to do something to a destroyed control, you will get a swtexception with the content "the control has been destroyed [8]". Check the code in listing 3-2.

Import org. Eclipse. SWT .*;

Import org. Eclipse. SWT. layout .*;

Import org. Eclipse. SWT. Widgets .*;

Public class broken

{

Public static void main (string [] ARGs)

{

Display display = New Display ();

Shell shell = new shell (Display );

Shell. setlayout (New rowlayout ());

Text text = new text (shell, SWT. Border );

Shell. open ();

While (! Shell. isdisposed ())

{

If (! Display. readanddispatch ())

{

Display. Sleep ();

}

}

System. Out. println (text. gettext (); // error!

Display. Dispose ();

}

}

Listing 3-2

The code can be compiled and run, but after the main window is closed, the following stack trace is printed on the console:

Org. Eclipse. SWT. swtexception: widget is disposed

At org. Eclipse. SWT. SWT. Error (SWT. Java: 2332)

At org. Eclipse. SWT. SWT. Error (SWT. Java: 2262)

At org. Eclipse. SWT. Widgets. widget. Error (widget. Java: 385)

At org. Eclipse. SWT. Widgets. Control. getdisplay (control. Java: 735)

At org. Eclipse. SWT. Widgets. widget. isvalidthread (widget. Java: 593)

At org. Eclipse. SWT. Widgets. widget. checkwidget (widget. Java: 315)

At org. Eclipse. SWT. Widgets. Text. gettext (text. Java: 705)

At broken. Main (version. Java: 24)

Let's say a few more times. If you run this program on Windows XP, the dialog box will pop up, saying that javaw.exe has a problem and needs to be closed. "You also need to ask" do you want to send an error report to Microsoft ?"

The content of this section is very simple: once an object is destroyed, whether it explicitly calls the dispose () function or its container is destroyed, don't worry about it (Leave it alone ).

[2]: This design avoids issues with calling methods on a code object when the underlying widget hasn' t yet been created, which can occur in other toolkits that don't match the lifecycles of the Code widget and the native widget.

[3] parent, the translator thinks that translation into a "Container" is more vivid.

[4]: Most guis require you to specify a parent for a widget before creating that widget, And the widget "belongs" to its parent throughout its lifecycle.

[5] original note: Carolyn MacLeod and Steve northover,SWT: The Standard Widget Toolkit-Part 2: Managing Operating System Resources, Www.eclipse.org/articles/swt-design-2/swt-design-2.html.

[6]: If you created it, you dispose it. Disposing the parent disposes the children.

[7]: original a logical cascade of automatic disposal

[8]: original widget has been disposed

 

Returned directory

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.