Getting Started with SWT and jface development in eclipse

Source: Internet
Author: User
Tags abstract add object constructor version variable window access
The Standard Widgets Toolbox (Standard widget TOOLKIT,SWT) and the JFace library can be used to develop graphical user interfaces for the ECLIPSE environment, and they can also be used to develop individual GUI native applications. In this article, I'll introduce some basic SWT (basic GUI object name) types and show you how to use them synthetically to create useful applications.

   about Eclipse, SWT, and JFace

As mentioned on Eclipse's Web site, Eclipse is a general-purpose tool platform. It is an open, extensible IDE that can be used for anything, and nothing special, it gives tool developers flexibility and control over software technology.

Eclipse provides a foundation for developers to produce a large number of GUI-driven tools and applications. This function is based on the GUI library SWT and JFace.

SWT is a library that creates a Java version of the local host operating system GUI control. It depends on the native implementation. This means that an SWT based application has several key features:

  • Their appearance, behavior, and execution are similar to "native" applications.
  • The Window widget (widget) provided reflects the widgets (components and controls) provided on the host operating system.
  • Any special behavior of the host GUI library is reflected in the SWT GUI.
      These goals make SWT different from Java Technology's swing,swing design goal is to eliminate operating system differences.

      The SWT library reflects the basic widget for the host operating system. In many environments, this approach is too low. The JFace library helps to add a large number of services to SWT applications. JFace does not hide swt, it just expands SWT. As you will see in the later part of this series, one of the most important extensions of SWT is to isolate the application's data model from the GUI that displays and changes it.

      Before I begin, I need to introduce some SWT terminology:

    1. Widget -The basic SWT GUI component (similar to the Component in Java AWT and the jcomponent in Swing). A Widget is an abstract class.
    2. control--a widget that has an operating system equivalent (in other words, has the same identity in the operating system). Control is an abstract class.
    3. composite--controls that contain other controls (similar to the Container in Java AWT and JPanel in Swing).
    4. Item -a widget that other controls contain (which may not be a composite control), such as lists and tables. Note that controls that contain items rarely contain other controls, and vice versa. Item is an abstract class. The
      widgets are arranged in the inheritance hierarchy. See Figure 1, Figure 2, and figure 3 to see how they are arranged. In Figure 2, the Basic1 class is the class from this article, and all the other classes are standard SWT widget.

      Figure 1. SWT Widget tree


      Figure 2. SWT Composite tree


      Figure 3. SWT Item list

       
      Note that Eclipse has cross-platform features (so it can run on many operating platforms), based on Eclipse's Microsoft? Windows? Version. Therefore, each of the examples included in this article should be able to be used on other platforms without any changes. Also note that this article is based on Eclipse V3.0. Little GUI widget types and attributes are added to Eclipse V3.1.
    5.   Basic controls

      Almost all SWT GUIs are created from some base section. All SWT widget widgets can be found in org.eclipse.swt.widget or in the org.eclipse.swt.custom package. (Some Eclipse plug-ins also provide customized widgets in other packages.) Window Widget package contains controls that are based on the operating system control, while the custom package contains some controls beyond the operating system control set. Some custom package controls are similar to controls in a widget package. To avoid naming conflicts, the name of a custom control starts with "C" (for example, comparing Clabel with Label).

      In SWT, all controls (except for some advanced controls, such as the shell, will be discussed later) must have a parent control (a composite instance) at the time of creation. When created, these controls are automatically "added" to the parent control, which is different from the controls that must be explicitly added to the parent control, and automatically adds a way to construct the GUI from top to bottom awt/swing. In this way, all controls can take a composite parent control (or a subclass) as an argument to the constructor.

      Most controls have some markup options that must be set at creation time. Therefore, most controls also have another constructor parameter, which we typically call a style, which provides a marker for setting these options. All of these parameter values are static final int , and are all defined in the org.eclipse.swt package's SWT class. If you do not need any parameters, you can use a SWT.NONE value.

        Label

      The label may be the simplest control, and the label is used to display plain text (text without color, special font, or style) or as a small image called an icon. The label does not accept the focus (in other words, the user cannot move to the label through the TAB key or the mouse), so the label cannot produce an input event.

      Listing 1 shows how to create a simple text label.

        Listing 1. Create a label with text

       import org.eclipse.swt.widget.*;  : Composite parent = ...;  : // create a center aligned label Label label = new Label(parent, SWT.CENTER);   


      Note that the text is set with a separate method different from the constructor. This is a typical symbol of all SWT controls. Only the parent control and the style are set in the constructor, and all other properties are set on the object that was created.

      Because of platform limitations, standard label controls cannot have both text and icons. To support both text and icons, you can use the Clabel control, as shown in Listing 2.
       
         Listing 2. Create a label that contains text and images

       import com.eclipse.swt.graphics.*; import org.eclipse.swt.widget.*; import org.eclipse.swt.custom.*;  : Composite parent = ...; Image image = ...;  : // create a left aligned label with an icon CLabel Clabel = new CLabel(parent, SWT.LEFT);   


         text

      While the label displays text, you often want to allow the user to insert text. The text control is used for this purpose. The text can be a single line (a text field), or it can be multiple lines (a text area). The text can also be read-only. There is no description in the text field, so they are often processed by the label control to determine their purpose. The text control can also contain a ToolTip that provides information about the purpose of the control (all controls support this feature).

      Listing 3 shows how to create a simple text field by using a limited number of attributes that are allowed to be used. The default text is selected for ease of erasure.

         Listing 3. Create a text that contains the selected default text and a restriction condition

       import org.eclipse.swt.widget.*;  : Composite parent = ...;  : // create a text field Text name = new Text(parent, SWT.SINGLE);   name.setText("<none>"); name.setTextLimit(50); name.setToolTipText("Enter your name -- Last, First");  name.selectAll();  


         Button

      Typically, you want the user to indicate when an action should be made. The most common practice is to use button controls. There are several styles of buttons:

        • Arrow--appears as an arrowhead pointing up, down, left, and right.
        • Check-a flagged checkmark.
        • FLAT -a button without a raised appearance.
        • PUSH -The instantaneous button (the most common event source).
        • RADIO --with an exclusive sticky mark (sticky mark), all other radio buttons are in the same group.
        • TOGGLE --a sticky button.

      Listing 4 Creates a "clear" button:

        Listing 4. Create a button

       import org.eclipse.swt.widget.*;  : Composite parent = ...;  : // create a push button Button clear = new Button(parent, SWT.PUSH);   


      In the name &Causes an accelerator to be created using the next letter, allowing the button to be pressed ctrl+< alphabetic > order (the Control order is determined by the host operating system).

         Event Listeners

      Typically, you might want to do something when you select a button, especially one of the push buttons. You can add one to this button by adding a SelectionListener(In org.eclipse.swt.eventsPackage) to do this. Events are generated when the button state changes (usually when the button is pressed). Listing 5 Prints a message when the Clear button is clicked.

         Listing 5. Button event handler

       import org.eclipse.swt.events.*;  : // Clear button pressed event handler clear.addSelectionListener(new SelectionListener() {      public void widgetelected(selectionEvent e) {         System.out.println("Clear pressed!");        }     public void widgetDefaultSelected(selectionEvent e) {         widgetelected(e);     


      This code uses an anonymous inner class, but you can also use the specified inner class or a separate class as the listener. Most contain two or more methods of ...ListenerClass also has a similar ...Adapterclass, which provides some empty method implementations and reduces the amount of code you need to write. For example, there is also a SelectionAdapterClass, this class implements the SelectionListener

      Note that the actions performed in these methods must be completed quickly (usually less than a second), or the GUI's response will be slow. Longer operations, such as accessing files, require a separate thread, but that is the subject of a later article.

        Composite Control

      So far, we've discussed some of the individual controls. In most GUIs, many controls are grouped together to provide a rich user experience. In SWT, this combination is implemented through the composite class.

      Composite controls can be nested at any level, and can mix and match controls and combine them as child controls. This can greatly reduce the complexity of GUI development and create opportunities for GUI code reuse (by encapsulating the internal GUI). Composite controls can be bounded, and these boundaries can easily be visually confusing, or they may be borderless and seamlessly integrated into larger groups.

      Listing 6. Creates a composite control with boundaries.

        Single 6. To create a composite control with boundaries

       import org.eclipse.swt.widget.*;  : Composite parent = ...;  


      In addition to boundaries, the Group composite subclass also supports headers. When defining exclusive button collections, groups are usually used to contain buttons of the radio type.

      Listing 7 creates a group with boundaries.

         Listing 7. Create a group with boundaries

       import org.eclipse.swt.widget.*;  : Composite parent = ...;  


         Shell

      A shell is a composite control (frame or window) that may not have a parent compound control, and it also has a Display as the parent control, which is usually the default setting. The shell has many different styles, but the most common style is SWT.SHELL_TRIMOr SWT.DIALOG_TRIM。 The shell can be modal or modeless. Modal shells are often used in dialog boxes to prevent the parent GUI (if any) from being processed before the child shell is closed.

      Listing 8 creates a frame-style top-level, modeless shell.

         Listing 8. Create a top-level shell

       import org.eclipse.swt.widget.*;  : Shell frame = new Shell(SWT.SHELL_TRIM);  


      A shell can have a child shell. These child shells are independent desktop Windows related to the parent shell (that is, all of its child shells will be closed if the parent shell is closed).

      Listing 9 creates a dialog-style child shell.

         Listing 9. Create a dialog box Shell

       : Shell dialog = new Shell(frame, SWT.DIALOG_TRIM);  


      See Figure 4 with SWT. Shell_trimsee's shell, as well as the SWT in Figure 5. Dialog_trim Shell to see how these values affect the cleanliness of the shell.

      Fig. 4. With SWT. Shell_trim's Shell



      Fig. 5. With SWT. Dialog_trim's Shell



         Layout Manager

      Composite controls often contain multiple controls. You can use the following two methods to schedule these controls:

        1. Absolute Positioning -set a clear X and Y position for each control and set a certain width and height by code.
        2. managed positioning -the X, Y, width, and height of each control are set by LayoutManager.


      In most cases, you should choose to use layoutmanagers because it is easy to adjust them to accommodate a variable sized GUI. SWT also provides a number of layout managers for you to use; In this installment of the series, we'll discuss two basic layout managers: Filllayout and GridLayout. In both cases, positioning is required whenever the size of the composite control is reset.

      Some layout managers are often allocated specifically for a single composite control. Some layout managers can be controlled using only their own parameters, while others require additional parameter--layoutdata, which is specified on each control in the composite control they manage.

        Filllayout

      Filllayout arranges controls in rows or columns. Each control is set to the same size as the width and height required to populate the composite control, and space is evenly distributed between the controls. A special case is that when there is only one child control, the size of the control is set to fill the size of the entire parent composite control.

        Listing 10. Use Filllayout to create a column of controls

       import org.eclipse.swt.widget.*; import org.eclipse.swt.layouts.*;  


         GridLayout

      GridLayout provides a more powerful layout approach, similar to the way you use HTML tables. It creates a cell in the 2-d grid. You can place a control in one or more cells, which you can call a cell span. The cell size can be equal, or a given variable percentage of the grid width or height. You can add a control to the next available column in a row, and if there are no more columns in the row, the control moves to the first column in the next row.

      Listing 11 creates a composite control that has two rows and two columns that contain two marked text fields. These columns can have different widths.

         Listing 11. Create a control Table

       import org.eclipse.swt.widget.*; import org.eclipse.swt.layouts.*;  


         Griddata

      Consider this: you need to specify how each control uses the remaining space in its cells. To provide this precise control for each cell, controls added to the managed composite control of GridLayout can have Griddata instances (Layoutdata subclasses).

      Listing 12 sets these text fields to take all the available space (according to the previous list).

         Listing 12. Configure a layout that extends to all available space


         Build a Running program

      Now it's time to take a look at all the SWT controls we've discussed in the simple executable example Basic1. See Resources for the full source code for the application.

      The SWT GUI requires a configured environment to run. This environment is provided through a display instance that provides access to the host operating system display device. This display instance allows you to process each user input (mouse or keyboard) to process your GUI.

      Listing 13 creates an environment and a GUI, and displays the GUI.

         Listing 13. Create a GUI application and start it

       import org.eclipse.swt.widget.*;  : Display display = new Display(); Shell shell = new Shell(display); shell.setText("Shell Title"); // *** construct Shell children here *** shell.open();       // open shell for user access // process all user input events while(!shell.isDisposed()) {    // process the next event, wait when none available    if(!display.readAndDispatch()) {        display.sleep();    } } display.dispose();  


      This code creates a window similar to Figure 6.

      Figure 6. Sample Application



         Concluding remarks

      In SWT and JFaceIn the first phase of the series, we introduced most of the basic SWT widget controls: Tags, text, buttons, composite controls, and shells. These controls, combined with display classes (displays Class), allow the creation of a fully functional GUI.

      Related Article

      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.