Reader small image

You're reading from  Eclipse Plug-in Development Beginner's Guide - Second Edition

Product typeBook
Published inAug 2016
Reading LevelExpert
Publisher
ISBN-139781783980697
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Alex Blewitt
Alex Blewitt
author image
Alex Blewitt

contacted on 30 aug 16 _____________ Dr Alex Blewitt has over 20 years of experience in Objective-C and has been using Apple frameworks since NeXTstep 3.0. He upgraded his NeXTstation for a TiBook when Apple released Mac OS X in 2001 and has been developing on it ever since. Alex currently works for an investment bank in London, writes for the on-line technology news site InfoQ and has published two other books for Packt publishing. He also has a number of apps on the Apple AppStore through Bandlem Limited. When he's not working on technology, and if the weather is nice, he likes to go flying from the nearby Cranfield airport. Alex writes regularly at his blog, http://alblue.bandlem.com, as well tweeting regularly from Twitter as @alblue. Acknowledgements This book would not have been possible without the ongoing love and support of my wife Amy, who has helped me through both the highs and lows of life. She gave me the freedom to work during the many late nights and weekends that it takes to produce a book and its associated code repository. She truly is the Lem of my life. I'd also like to thank my parents, Ann and Derek, for their encouragement and support during my formative years. It was this work ethic that allowed me to start my technology career as a teenager and to incorporate my first company before I was 25. I'd also like to congratulate them on their 50th wedding anniversary in 2015, and I look forward to reaching that goal with Amy. Thanks are due especially to the reviewer of this version of the book: Antonio Bello, as well as the previous version of this book: Nate Cook, James Robert and Arvid Gerstmann, who provided excellent feedback on the contents of this book during development and caught many errors in both the text and code. Any remaining errors are my own. I'd also like to thank my children Sam and Holly for inspiring me and hope that they too can achieve anything that they set their minds to. Finally, I'd like to thank Ben Moseley and Eren Kotan, both of whom introduced me to NeXT in the first place and set my career going on a twenty year journey to this book.
Read more about Alex Blewitt

Right arrow

Chapter 3. Creating JFace Viewers

JFace – the Eclipse model/view/controller architecture

In the last chapter, we looked at the basic building blocks of SWT, which provide a glue layer between the native operating system's widgets and Java. We will now look at JFace, which builds upon SWT to provide an MVC architecture as well as many of the common widgets used by Eclipse.

In this chapter, we shall:

  • Create a view for showing hierarchical data

  • Use image, font, and color resources

  • Generate styled text

  • Sort and filter entries in viewers

  • Add double-click actions

  • Create a view for showing tabular data

  • Synchronize selections between views

Why JFace?


While SWT provides generic implementations for basic widgets (such as trees, buttons, labels, and so on), these often work at a level that deals with strings and responds to selection by integer index. To make it easier to display structured content, JFace provides several viewers that provide combinations of SWT widgets and event managers to provide a UI for structured content.

There are many types of viewer—which are all subclasses of Viewer—but the most common ones are ContentViewer subclasses such as TreeViewer and TableViewer. There are also text-based viewers such as TextViewer and SourceViewer, as well as operational views such as DetailedProgressViewer for the Progress view. In this chapter, we will create views based on TreeViewer and TableViewer. Since JFace is based on SWT (described in Chapter 2, Creating Views with SWT), knowing how SWT works is essential to understand how JFace is used.

Creating TreeViewers


Many views in Eclipse use a tree-like view, from a file navigator to the contents of source files. The JFace framework provides a TreeViewer, which provides the basic tree navigation functionality. This will be used to implement a TimeZoneTreeView.

Time for action – creating a tree viewer


As with the previous chapter, a new TimeZoneTreeView class will be created using the plugin.xml editor, as an E4 view. This will show time zones, organized hierarchically by region.

  1. Right-click on the com.packtpub.e4.clock.ui project and navigate to Plug-in Tools | Open Manifest if it's not open already.

  2. Open the Extensions tab and go to the org.eclipse.ui.views entry. Right-click on this, navigate to New | e4view, and fill in the following:

    1. ID: com.packtpub.e4.clock.ui.views.TimeZoneTreeView

    2. Name: Time Zone Tree View

    3. Class: com.packtpub.e4.clock.ui.views.TimeZoneTreeView

    4. Category: com.packtpub.e4.clock.ui

    5. Icon: icons/sample.gif

  3. An entry is created in the plugin.xml file that looks like:

    <e4view
      category="com.packtpub.e4.clock.ui"
      class="com.packtpub.e4.clock.ui.views.TimeZoneTreeView"
      icon="icons/sample.gif"
      id="com.packtpub.e4.clock.ui.views.TimeZoneTreeView"
      name="Time Zone Tree View"
      restorable="true">
    </e4view>
  4. On the...

Time for action – using Images in JFace


The TimeZoneLabelProvider can return an SWT Image. Although they can be loaded dynamically as in the previous chapter, JFace provides a number of resource registries that can be used to manage a set of resources for the application. Standard registries include the ImageRegistry, FontRegistry, and ColorRegistry classes. The purpose of a resource registry is to maintain a list of Resource instances and ensure that they are correctly disposed when they are no longer needed.

JFace has a set of these global registries; but there are specific ones, for example, those used by the IDE to maintain folder and file type icons. These use resource descriptors as a lightweight handle for the resource, and a means to acquire an instance of the resource based on that descriptor. The returned resource is owned by the registry, and as such, should not be disposed by clients that acquire or use them.

Standard images can be acquired by injecting an ISharedImages instance...

Time for action – styling label providers


The IStyledLabelProvider is used to style the representation of the tree viewer, as used by the Java outline viewer to display the return type of the method, and by the team's decorator when showing when changes have occurred.

  1. Add the IStyledLabelProvider interface to the TimeZoneLabelProvider class, and create the getStyledText method. If the selected element is a Map.Entry that contains a ZoneId, add the offset afterwards in brackets:

    public class TimeZoneLabelProvider extends LabelProvider
     implements IStyledLabelProvider {
      public StyledString getStyledText(Object element) {
        String text = getText(element);
        StyledString styledString = new StyledString(text);
        if (element instanceof ZoneId) {
          ZoneId zone = (ZoneId)element;
          ZoneOffset offset = ZonedDateTime.now(zone).getOffset();
          styledString.append(" (" + offset + ")",
           StyledString.DECORATIONS_STYLER);
        }
        return styledString;
      }
    }
  2. In order to use the styled...

Sorting and filtering


One of the features of JFace is that ordering of the data can be processed by the view, rather than having the data pre-processed. This makes it easy to present sorted or filtered views, where the user either searches for a particular term, or performs a sort in a different manner. These filters are used heavily in the Eclipse IDE, where options such as Hide libraries from external and Hide closed projects can be found in many of the drop-down actions for the view.

Time for action – sorting items in a viewer


The TreeViewer already shows data in a sorted list, but this is not a view-imposed sort. Because the data is stored in a TreeMap, the sort ordering is created by the TreeMap itself, which in turn is sorting on the value of the toString method. To use a different ordering (say, based on the timezone offset) the choices are either to modify the TreeMap to add a Comparator and sort the data at creation time, or add a sorter to the TreeViewer. The first choice is applicable if the data is only used by a single view, or if the data is coming from a large external data store which can perform the sorting more efficiently (such as a relational database). For smaller data sets, the sorting can be done in the viewer itself.

  1. JFace structured viewers allow view-specific sorting with the ViewerComparator. Create a new subclass called TimeZoneViewerComparator in the com.packtpub.e4.clock.ui.internal package, and implement the compare method as follows:

    public...

Time for action – filtering items in a viewer


Another common feature of viewers is filtering. This is used both when performing a manual search, as well as for filtering specific aspects from a view. Quite often, the filtering is connected to the view's menu, which is the drop-down triangle on the top right of the view, using a common name such as Filters. The ViewerFilter class provides a filtering method, confusingly called select (there are some filter methods, but these are used to filter the entire array; the select is used to determine if a specific element is shown or not).

  1. Create a class TimeZoneViewerFilter in the com.packtpub.e4.clock.ui.internal package, which extends ViewerFilter. It should take a String pattern in the constructor, and return true if the element is a TimeZone with that pattern in its display name:

    public class TimeZoneViewerFilter extends ViewerFilter {
      private String pattern;
      public TimeZoneViewerFilter(String pattern) {
        this.pattern = pattern;
      }
      public...

Interaction


Being able to display data is one thing, but invariably views need to be interactive. Whether that's hooking up the sort or filter functionality from the previous chapter, or seeing information about the selected item, views must be interactive not only for exploring data, but also for working with data.

Time for action – adding a double-click listener


Typically, a tree view is used to show content in a hierarchical manner. However, a tree on its own is not enough to be able to show all the details associated with an object. When the user double-clicks on an element, more details can be shown.

  1. At the end of the create method in TimeZoneTreeView, register a lambda block that implements the IDoubleClickListener interface with the addDoubleClickListener method on the treeViewer. As with the example in Chapter 1, Creating Your First Plug-in, this will open a message dialog to verify that it works as expected:

    treeViewer.addDoubleClickListener(event -> {
        Viewer viewer = event.getViewer();
        Shell shell = viewer.getControl().getShell();
        MessageDialog.openInformation(shell, "Double click",
         "Double click detected");
    });
  2. Run the target Eclipse instance, and open the Time Zone Tree View. Double-click on the tree, and a shell will be displayed with the message Double click detected....

Tabular data


The tree viewer is used in many situations in Eclipse, but sometimes being able to display more information for a single element is required. JFace provides a TableViewer which is similar to the TreeViewer, except that instead of a single label there are multiple columns available. There is also a combined TableTreeViewer, which combines functionality from the two classes.

Time for action – viewing time zones in tables


To display the time zones in tabular form, a new view will be created called Time Zone Table View.

  1. Right-click on the com.packtpub.e4.clock.ui project and navigate to Plug-in Tools | Open Manifest. Open the Extensions tab and right-click on the org.eclipse.ui.views, followed by navigating to New | e4view and filling in the following:

    1. ID: com.packtpub.e4.clock.ui.views.TimeZoneTableView

    2. Name: Time Zone Table View

    3. Class: com.packtpub.e4.clock.ui.views.TimeZoneTableView

    4. Category: com.packtpub.e4.clock.ui

    5. Icon: icons/sample.gif

  2. The plugin.xml should now contain:

    <e4view
     category="com.packtpub.e4.clock.ui"
     class="com.packtpub.e4.clock.ui.views.TimeZoneTableView"
     icon="icons/sample.gif"
     id="com.packtpub.e4.clock.ui.views.TimeZoneTableView"
     name="Time Zone Table View"
     restorable="true">
    </e4view>
  3. Create the class using the editor's short-cuts to create a new class TimeZoneTableView in the com.packtpub.e4.clock.ui.views package, or...

Selection


Selection in Eclipse is handled using two distinct implementations. The original Eclipse workbench implementation, along with JFace, uses interfaces such as ISelection and IStructuredSelection to represent a selected object. The Eclipse 3.x Platform UI provided an ISelectionService to keep track of a global selected object in the current window.

Since both JFace and the Eclipse Platform UI depend upon SWT, the traditional selection service was tied to a specific implementation of the graphics library, which limited its use outside of SWT. As a result, the ESelectionService was created to provide closer ties with the E4 platform, without the SWT/JFace dependencies. Both of these selection mechanisms are seen in modern Eclipse applications.

Time for action – propagating selection


When the user selects an item in a viewer component, any registered selection listeners will be notified. In order to forward changes to the E4 selection service, a listener needs to be created to forward the selection to the ESelectionService.

  1. Add the required packages to the bundle's package imports, by right-clicking on the com.packtpub.e4.clock.ui project and navigating to Plug-in Tools | Open Manifest to open the bundle's manifest. On the Dependencies tab, click on Add under the Imported Packages section and enter org.eclipse.e4.ui.workbench.modeling as well as org.eclipse.e4.core.di.annotations.

  2. In order to forward selection changes to the E4 selection service, it must be injected into the view. Add a field ESelectionService selectionService annotated with @Inject and @Optional. When the part is created, the field will be filled with a selection service instance or null as appropriate:

    @Inject
    @Optional
    private ESelectionService selectionService...

Time for action – responding to selection changes


When the selection is changed in the E4 selection service, parts can be notified that a new selection is available through injection. Although an @Inject field could be used, there would be no trigger that could be used to update the view. Instead, a method with an injected parameter will be used to trigger the update.

  1. Add the required packages to the bundle's package imports, by right-clicking on the com.packtpub.e4.clock.ui project and navigating to Plug-in Tools | Open Manifest to open the bundle's manifest. On the Dependencies tab, click on Add under the Imported Packages section and enter org.eclipse.e4.ui.services.

  2. In the TimeZoneTableView class, create a method called setTimeZone. The method name isn't specifically important, but the method needs to be annotated with @Inject and @Optional, and the argument needs to be annotated with @Named(IServiceConstants.ACTIVE_SELECTION). It should look like:

    @Inject
    @Optional
    public void setTimeZone...

Summary


This chapter covered how to use JFace to build viewers for structured data: both tree-based views (with a TreeViewer) and table based views (with a TableViewer). It also covered some JFace built-in features for managing fonts and images.

To synchronize data between views in Eclipse, services such as the ISelectionService are used (or in E4, the ESelectionService). Having views generate and consume selection events provides a visual consistency even though the views may be exposed by different plug-ins. The next chapter will look at how to interact with the user, with menus, commands and handlers.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Eclipse Plug-in Development Beginner's Guide - Second Edition
Published in: Aug 2016Publisher: ISBN-13: 9781783980697
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Alex Blewitt

contacted on 30 aug 16 _____________ Dr Alex Blewitt has over 20 years of experience in Objective-C and has been using Apple frameworks since NeXTstep 3.0. He upgraded his NeXTstation for a TiBook when Apple released Mac OS X in 2001 and has been developing on it ever since. Alex currently works for an investment bank in London, writes for the on-line technology news site InfoQ and has published two other books for Packt publishing. He also has a number of apps on the Apple AppStore through Bandlem Limited. When he's not working on technology, and if the weather is nice, he likes to go flying from the nearby Cranfield airport. Alex writes regularly at his blog, http://alblue.bandlem.com, as well tweeting regularly from Twitter as @alblue. Acknowledgements This book would not have been possible without the ongoing love and support of my wife Amy, who has helped me through both the highs and lows of life. She gave me the freedom to work during the many late nights and weekends that it takes to produce a book and its associated code repository. She truly is the Lem of my life. I'd also like to thank my parents, Ann and Derek, for their encouragement and support during my formative years. It was this work ethic that allowed me to start my technology career as a teenager and to incorporate my first company before I was 25. I'd also like to congratulate them on their 50th wedding anniversary in 2015, and I look forward to reaching that goal with Amy. Thanks are due especially to the reviewer of this version of the book: Antonio Bello, as well as the previous version of this book: Nate Cook, James Robert and Arvid Gerstmann, who provided excellent feedback on the contents of this book during development and caught many errors in both the text and code. Any remaining errors are my own. I'd also like to thank my children Sam and Holly for inspiring me and hope that they too can achieve anything that they set their minds to. Finally, I'd like to thank Ben Moseley and Eren Kotan, both of whom introduced me to NeXT in the first place and set my career going on a twenty year journey to this book.
Read more about Alex Blewitt