Sei sulla pagina 1di 51

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Lars Vogel
Version 7.0 Copyright 2007, 2008, 2009, 2010, 2011, 2012 Lars Vogel by Lars Vogel Tutorial
327

08.05.2012
Revision History Revision 0.1 - 0.7 14.08.2007 - 03.09.2007 Lars Vogel

Eclipse RCP with Eclipse 3.3 Revision 0.8 - 7.0 03.11.2008 - 08.05.2012 Lars Vogel

Several bug fixes and enhancements

Eclipse RCP This tutorial describes how to develop Eclipse RCP applications. It is based on Eclipse 3.7 (Eclipse Indigo).

Table of Contents
1. Eclipse based Applications 1.1. What are Eclipse RCP applications? 1.2. Advantages of Eclipse based applications 2. Eclipse 3.x vs. Eclipse 4.x 3. What are Extension Points?

1 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

6. Installation 6.1. Java 6.2. Download the Eclipse plug-in package 6.3. Update an Eclipse Java IDE 7. Approach 8. Tutorial: Create your first RCP application 8.1. Create an RCP application 8.2. Start an RCP application 9. Tutorial: Create and Launch Product 9.1. Create your product configuration 9.2. Launch your product 10. Overview 11. Specifying Arguments 12. Common run configuration problems 13. Application and Advisor Classes 14. Products and Branding 14.1. Product and application 14.2. Dependencies 14.3. Configuration 15. Deployment 15.1. Overview 15.2. Which artifacts are included in the export? 15.3. Exporting the product 15.4. Export for multiple platforms via the delta pack 15.5. Including the required JRE into the export 16. Common product export problems 17. WorkbenchParts and Perspectives 17.1. WorkbenchParts - Views and Editors 17.2. Perspective 18. Convention 19. Tutorial: Adding Views to your application 19.1. Create a view 19.2. Add the view to your perspective 19.3. Result 19.4. Add view to perspective via code 20. SWT 21. JFace Viewers 22. Commands 23. Tutorial: Adding an Perspectives 24. Tutorial: System Tray 25. Target Platform 25.1. Developing against the Eclipse IDE 25.2. Defining your Target Platform

2 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

27. Tips and Tricks 27.1. Load an image from your plugin 27.2. Save users layout 27.3. Accessing the status line 27.4. Finding unused dependencies 27.5. Multi-User settings 28. Reading resources from plug-ins 29. Questions and Discussion 30. Links and Literature 30.1. Source Code 30.2. Eclipse Resources 30.3. vogella Resources

1.1. What are Eclipse RCP applications?


Eclipse was originally started as a modular IDE application. In 2004 the Eclipse version 3.0 was released. Eclipse 3.0 supported the re-use of the Eclipse platform to build stand-alone applications based on the same technology as the Eclipse IDE. At this point the term "Eclipse RCP" was coined. Eclipse RCP is short for "Eclipse Rich Client Platform" and indicates that the Eclipse platform is used as a basis to create feature-rich stand-alone applications. The Eclipse 4 platform simplifies and unifies the Eclipse programming model and extends the concept of building Eclipse based applications with new technologies, like dependency injection and declarative styling via CSS files.

1.2. Advantages of Eclipse based applications


The Eclipse platform forms the basis of the most successful Java IDE and therefore is very stable and broadly used. It uses native user interface components which are fast and reliable and with its strong modularity approach it allows to design component based systems. Companies like IBM and Google use the Eclipse framework for their products and therefore ensure that

3 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

The Eclipse platform also fosters a large community of individuals which provide support, information and extensions to the Eclipse framework. Tapping into this Ecosystem allows you to find required resources and information.

The following describes how to build Eclipse RCP applications based on the Eclipse 3.x programming model. Eclipse 4 makes significant changes to this programming, please see Eclipse 4 Tutorial for an introduction into the Eclipse 4 programming model. Currently development with Eclipse 3.x programming model is much more stable and has better tool support then developing for Eclipse 4.x programming model. On the other hand the Eclipse 4.x programming model is much more flexible and simpler to use.

Extension-points define interfaces for other plug-ins to contribute functionality (code and non-code). They are defined in the "plugin.xml" file, which must be in the root directory of your plug-in project. Existing extensions (contributions) are collected during the start of an Eclipse application.

The minimal required plug-ins to create and run an minimal Eclipse RCP application (with UI) are the two plugins "org.eclipse.core.runtime" and "org.eclipse.ui". Based on these components an Eclipse RCP application must define the following elements: Main program - A RCP main application class implements the interface "IApplication". This class can be viewed as the equivalent to the main method for standard Java application. Eclipse expects that the application class is defined via the extension point "org.eclipse.core.runtime.application".

4 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

"org.eclipse.ui.perspective".

Trainings

Books

Connect

Workbench Advisor- invisible technical component which controls the appearance of the application (menus, toolbars, perspectives, etc) The Eclipse application is the equivalent of the Java main() method. Applications are defined via the extension point org.eclipse.core.runtime.applications and must extend IApplication.

The following assumes that you already have some knowledge in using the Eclipse IDE for standard Java development. See Eclipse IDE Tutorial if you don't have this knowledge. Is also assume that you are familiar with using the Eclipse update manager. See Eclipse Update Manager to learn how to use it.

6.1. Java
The following description assumes that you have already Java installed. If not please download and install the most current version before continuing with this chapter. To find instructions how to install Java, please google for "How to installed Java for MyOS", while replacing "MyOS" with the Operating System your are using.

6.2. Download the Eclipse plug-in package


Browse to Eclipse download site and download the package "Eclipse for RCP and RAP Developers". Extract the download to your harddisk. Avoid having special characters or spaces in the path to Eclipse.

6.3. Update an Eclipse Java IDE


In case you have downloaded the Eclipse Java IDE (or any other non RCP flavor) distribution you can

5 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Install General Purpose Tools Eclipse Plug-in Development Environment Eclipse RCP Plug-in Developer Resources from the Eclipse update site for your release. You may have to remove the "Group items by category" flag to see all available features.

6 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

If you teach programming you basically have two extreme choices. The first approach is that you explain everything first and then do it. The second choice is that you first do everything and then explain what you have done. The following description tends towards the second approach. We will develop a small RCP application, create a product and launch it, before explaining the project structure, the involved classes and what a product or a launch configuration is. In my experience its easier to understand an explanation, if you have already created an example. The risk associated with that approach is that if you run into a problem you don't know how to solve it. Therefore if you have problem starting your product, I suggest to read the chapter about launch configurations and if that doesn't help, check the "Products and Branding" chapter.

8.1. Create an RCP application


The following explains how to create a simple RCP application. In Eclipse select File-> New Project. From the list select "Plug-In Project".

7 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Give your plugin the name "de.vogella.rcp.intro.first" .

8 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Press "Next" and make the following settings. As we are going to develop an RCP application, select "Yes" at the question "Would you like to create a rich client application".

9 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Press next and select the template "Hello RCP" .

10 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Press next and select "Add branding" and press Finish.

11 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

especially the Java files to get a first feeling about the project structure.

Tutorials

Trainings

Books

Connect

8.2. Start an RCP application


While it is possible in Eclipse 3.7 to start an application directly, it is consistent to create a product to start the application. Therefore we will not run the application directly but create first an product. This is also in line with Eclipse 4.x. In Eclipse 4.x you cannot start an Application directly, you always need a product.

12 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Right-click on your "de.vogella.rcp.intro.first" project and select New Product Configuration .

Name your product configuration "de.vogella.rcp.intro.first.product". Select "Create a configuration file with basis settings". Press finish. Open the file de.vogella.rcp.intro.first.product" and select the "Overview" tab. Enter the name "DeployTest". Leave the ID empty. The name is the default which will be displayed in the title of the window, the ID is not required and entering it leads sometimes to problems. You can change this default name in class ApplicationWorkbenchWindowAdvisor in the method preWindowOpen() via the configurer.setTitle("New title");)

Press "New" in the "Product Definition" part and select the application of your plugin "de.vogella.rcp.intro.first.application".

13 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

As a result the "Product Definition" part of the overview tab should now be filled with your selection. The product identifier is stored as the extension "org.eclipse.core.runtime.product" in the file "plugin.xml". Switch to the "Dependencies" Tab and click the Add button. Add your application plug-ins. Press the button "Add Required Plug-ins" to add all dependent plug-ins to your product. Save. Optional create a "splash.bmp" via your favorite graphics tool and save it in the project with contains the product. Also add a message and a progress bar to your splash screen.

14 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

9.2. Launch your product


On the overview tab press synchronize and then press "Launch an Eclipse application". Make sure your product starts. The result should look like the following:

Congratulations, you have created and started your first RCP application.
Java program for Freshers Programs in Core java,Advanced java and Java EE. Enroll today ! Talentedge.in Flipkart Official Site Get 1TB - 3TB Harddisks @Huge Discounts Easy EMI & Payment Option www.Flipkart.com/Harddisk Java Application Code and Debug Your Apps On The Fly In The Cloud. Download the Trial windowsazure.com

A run configuration in Eclipse defines the environment under which an Eclipse application will be started. For example it defines compiler flags, plug-in (classpath) dependencies etc. Sometimes a run configuration is called "launch configuration". If you start your Eclipse application, using the link in the product file, the run configuration will be

15 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

You can use the created run configuration directly for starting the application again. Changes in the product configuration file will not be considered. You can update the run configuration by starting the application from the product definition again. To see and edit your run configuration select your product configuration file, right-click on it and select Run As Run Configurations... . On the "Main" tab in the field "location" you specify where the Eclipse IDE will create the files necessary to start your Eclipse based application.

16 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

The run configuration allows to add additional parameters for your application on the Arguments tab. Per default the -consoleLog parameter is included. This will write error messages of the running Eclipse application instance to the Eclipse IDE "Console" View.

If you provide different translations for your Eclipse application, you can specify the language for your application via the -nl parameter. For example -nl will start your application with the English language. This is useful to test your application with different languages. Other useful parameters are -console (which will give you a OSGi console where you can check the status of your application) and -noExit (which will keep the OSGi console open even if the application crashes).

Run configurations are frequent sources of problems. The most common problem is that required plug-ins are missing. Eclipse can check this automatically for you before every start. On the Plug-ins Tab select the Validate plug-ins prior to launching option. This will check if you have all required plug-ins in your run configuration. If this check reports that some plug-ins are missing, try clicking the Add Required Plug-Ins button. Also make sure to define all dependencies in your product.

17 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

The following table lists potential problems and solutions. Table 1. Common problems with Run Configuration
Problem During start you get error messages like "One or more bundles are not resolved because the following root constraints are not resolved" or "java.lang.RuntimeException: No application id has been found." Strange behavior but no error message. How to investigate or solve Check that all required plug-ins are included in your run configuration. Make sure that your product defines dependencies to all required plug-ins or features. Check if your run configuration includes the parameter -consoleLog. This option allows to see errors of the Eclipse based application in the console view of the Eclipse IDE. Make sure that your product includes all

Runtime configuration is frequently missing required plug-ins

18 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect
required dependencies.

A change in the product dependencies, e.g. a new plug-in is added, is not included in the run configuration.

A product updates an existing run configuration if you start the product directly from the product definition file. If you select the run configuration directly it will not be updated.

During the startup of an Eclipse RCP application the Eclipse runtime will evaluate which class is defined via the org.eclipse.core.runtime.application extension point. This is the equivalent of the main class of standard Java programs. This class is responsible for creating the SWT Display and for starting the event loop for the application. This class is typically called Application and must implement the interface IApplication.
Display display = PlatformUI.createDisplay(); PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());

PlatformUI.createAndRunWorkbench() creates and runs a Workbench. The Workbench

represents the graphical user interface of Eclipse. The visual part of the Workbench is represented via the WorkbenchWindow class. A Workbench can have several WorkbenchWindows opened. The inner part of the WorkbenchWindow is represented via the class WorkbenchPage. The Workbench is configured via a class of type WorkbenchAdvisor. This class defines the initial Perspective and defines the WorkbenchWindowAdvisor class.
WorkbenchWindowAdvisor calls the class ActionBarAdvisor which configures Actions for the Workbench and defines initial attribute for the WorkbenchWindow as initial size, title and visibility of the

statusline.

19 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials
}

Trainings

Books

Connect

public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); configurer.setInitialSize(new Point(400, 300)); configurer.setShowCoolBar(false); configurer.setShowStatusLine(false); configurer.setTitle("Todo"); //$NON-NLS-1$ }

For example you could set the initial position of the application via postWindowCreate() method.

// For further info see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84938 @Override


public void postWindowCreate() { Shell shell = getWindowConfigurer().getWindow().getShell(); shell.setLocation(100, 400); super.postWindowCreate(); }

The ActionBarAdvisor class is as of Eclipse 3.7 not important any more as the Action framework is replaced by the superior command framework. Each adviser allow to configure certain behavior of the application, e.g. the WorkbenchAdvisor allows to perform certain actions at startup or shutdown by overriding the preStartUp() and preShutdown() methods. .

14.1. Product and application


A product configuration (short: product) defines all resources that goes with your Eclipse application, e.g. icons, splash screen, external jars, other plugins, etc. The product is a development artifact which describes the content of your application and is not required at runtime. A product always points to one Application class. This Application class must implement the

20 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

You define your product configuration via a ".product" file. A product configuration file can be created via a right-click on your project and select New Product Configuration. This configuration file contains all the information about required plug-ins, configuration files, resources etc. The configuration file is used for exporting / creating your product. It is recommended to leave the product ID blank, because the product export may have issues if the product ID is the same as a plug-in ID. On the overview tab of your product you can start the product and select the "Synchronize" link. This selection will write the product configuration, which is required at runtime, into the plugin.xml file.

14.2. Dependencies
A product configuration file can either be based on plug-ins or features. This setting is done on the "Overview" tab of the product configuration file.

On the dependency tab you maintain the plug-ins or features your products consists of. A product will not do any automatic dependency resolution for you. If you add a plug-in to your product and want to

21 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

14.3. Configuration
The Splash tab allows to specify the plug-in which contains the splash screen. You need to put the splash.bmp file into the project main directory. This name and directory is predefined in Eclipse, but can be changed via the osgi.splashPath parameter.

You can configure the launcher name and icon for your exported product. The launcher is the executable program that is created during the deployment of the product. A launcher is platform specific. For example eclipse.exe on the Windows platform. This launcher has also an icon associated with it. To change the name and the icon, select the Launcher tab of your product configuration. Here you can specify the file name of the launcher and the icon which should be used. Make sure the size of the icons is correctly maintained otherwise Eclipse will not use these icons.

22 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

In the launcher section you can also specify parameters to your Eclipse application or arguments to the Java runtime environment.

15.1. Overview
Your product configuration file can be used to export your application to run outside of Eclipse. Exporting your product will create a directory or a zipped file which contains all artifacts required to run your application. It will also contain a native launcher specific to the platforms, e.g. Windows or Linux, you have exported it for. The resulting directory can be shared with others.

23 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

The included artifacts are defined by the "build.properties" file. Eclipse will per default add the compiled Java classes. You have to add other files manually, e.g. icons or splash screen images. To change the "build.properties" file you can use the "plugin.xml" editor. Open the "plugin.xml" file and select the build tab. Make sure the META-INF directory, the plugin.xml file and all other static files, e.g. icons, splash.bmp and in the case of an Eclipse 4 application the Application.e4xmi file and potentially CSS files, are flagged to be included in the exported product. An Eclipse application started from the Eclipse IDE will have access to resources which are not contained in the build.properties, but these files will not be contained in the exported application. Your exported application will therefore fail to find the files. Therefore it's a good rule to directly include new resources in the configuration.

15.3. Exporting the product


To export the product switch to your product configuration file, select the Overview tab and click on the Eclipse Product export wizard link. On the second page of the wizard you can specify the destination directory and the root directory for the exported application. This root directory will be a sub-folder in the destination directory and will contain the complete application. The following screenshots show the export wizard in action.

24 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

25 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

should start your application.

Tutorials

Trainings

Books

Connect

If you transfer the content of this directory to another machine (with the same architecture, e.g. Linux 64 bit) your application should run on this machine. The machine only needs to have Java installed. The export dialog allows to create an archive file directly, which makes it easier to transfer all files to another machine.

15.4. Export for multiple platforms via the delta pack


The delta pack is a separate download and can be added to your Eclipse installation via the settings in the target platform. If the delta pack is available, you can export for multiple platform.

15.5. Including the required JRE into the export


You can also deploy your own RCP application bundled with a JRE to make sure that a certain JRE is used. An Eclipse application first searches in the installation directory for a folder called jre and for a contained Java-VM. If it finds one, then this JRE is used to start the Eclipse application. To include the JRE from your running environment, select the Bundle JRE for this environment with the product flag on the Launching tab of your product configuration file.

If the export encounters a problem please have a look into the following table for a solution: Table 2. Problems with the product export
Problem Export fails Possible cause Try using an empty target directory, sometimes the export cannot delete the existing files and therefore fails. Check the flag "The product includes native launcher artifacts" in your .product file on the "Overview" tab. Validate that all dependencies are included in the product. Delete an existing launch

No .exe file after the export Product could not be

26 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials
found

Trainings

Books

Connect

configuration and restart the product from the IDE to see if everything is configured correctly. Check build.properties to see if all required images and icons are included in the export.

Splash Screen or other icons are missing Splash Screen is missing

Ensure that you have entered the defining plug-in in the "Splash" tab on the product configuration file. Not defining it works, if you start the plug-in from Eclipse, but not if you start the exported product. Check the log file in the workspace folder of your export product to see the error messages during startup. Alternatively add the "-consoleLog" parameter to the ".ini" file in folder of the export product. Check build.properties to see if the Application.e4xmi and the plugin.xml are included in the export. Make sure that the service start level is set to "auto" so that the bundle which defines the OSGi service is started. Also make sure that the org.eclipse.equinox.ds bundle is started before your bundle which define a service via declarative services. Check the "build.properties" file of the plug-in which provides the property files, if the property files are included in the export.

Issues during startup

applicationXMI argument is missing Service could not be found or injected

Translations not available in the exported product

17.1. WorkbenchParts - Views and Editors


As described earlier the WorkbenchWindow and the WorkbenchPage represent the visual and inner part of the graphical user interface.

27 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Views are used to display information in an RCP application; they can also be used to change data. Views extend the abstract class ViewPart. Editors extend the abstract EditorPart. Both extend WorkbenchPart.

An editor typically requires that the user explicitly select "save" to apply the changes to the data while a view typically changes the data immediately. All editors are opened in the same area. Via the perspective you can configure if the editor area is visible or not.
Views and Editors are defined via extension points in the file "plugin.xml" via the tab "Extensions". Views are defined via the extension point "org.eclipse.ui.views" and Editors via the extension point

"org.eclipse.ui.editors".
Views must implement the createPartControl() and setFocus() methods. createPartControl() is used to create the UI components of the View.

createPartControl() will get as parameter a Composite which can be used to construct the user interface. This composite has per default a FillLayout layout manager assigned to it. This layout manager assigns the same space to all components equally.
setFocus() must set the focus to a specific UI component.

17.2. Perspective
A Perspective describes a certain configuration of Views and Editors. A Perspective is defined via "org.eclipse.ui.perspectives". The WorkbenchParts which are part of a
Perspective are either defined via a Java class defined in the extension point

"org.eclipse.ui.perspectives" or via the "org.eclipse.ui.perspectiveExtensions".


public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { layout.addView("de.vogella.rcp.intro.first.MyView", IPageLayout.TOP, IPageLayout.RATIO_MAX, IPageLayout.ID_EDITOR_AREA); } }

28 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

layout.addView() adds a view to the perspective. You can also add placeholders for views via the layout.addPlaceholder() method call. This methods accepts wildcards and a View with a matching

ID would open in this area. For example if you want to open all views in a specific place you could use the layout.addPlaceholder("*",...) method call, or
layout.addPlaceholder("view_id",....) to open a View with the "view_id" ID in this placeholder.

You can also group view via a IFolderLayout which can be created via layout.createFolder() call and by adding Views to this folder via the addView(id) method on IFolderLayout.

In this tutorial we will always create RCP applications. Therefore if the instruction says "Create an RCP project" you should create a new plug-in project with the flag "Would you like to create a rich client application" enabled.

19.1. Create a view


The following will explain how to add views to your application. We will continue to use the RCP project "de.vogella.rcp.intro.first". Add the extension "org.eclipse.ui.views" to your plugin. Select ""plugin.xml" and the tab "Extentions". Right mouse-click on your new view extension and select New -> View. Maintain the id "de.vogella.rcp.intro.view.MyView" and the class "de.vogella.rcp.intro.view.MyView".

29 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Create the class "MyView" by clicking on the "class" hyperlink and maintain the following code. Afterwards your view is ready to be used.
package de.vogella.rcp.intro.first; import import import import org.eclipse.swt.SWT; org.eclipse.swt.widgets.Composite; org.eclipse.swt.widgets.Text; org.eclipse.ui.part.ViewPart;

public class MyView extends ViewPart {

@Override
public void createPartControl(Composite parent) { Text text = new Text(parent, SWT.BORDER); text.setText("Imagine a fantastic user interface here"); }

@Override
public void setFocus() { } }

19.2. Add the view to your perspective


You have to add the view to your perspective. Add the extension "org.eclipse.ui.perspectiveExtensions" to your plugin.

30 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Right click "*(perspectiveExtension)" -> New -> view". Maintain your view id "de.vogella.rcp.intro.first.MyView". Make the view relative to "org.eclipse.ui.editorss" which is the currently invisible editor area and make the view use all the space by selecting the maximum ratio of "0.95f".

19.3. Result
Run your application to see the result.

31 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

19.4. Add view to perspective via code


I personally prefer extension points over code. But instead of using the extension point "org.eclipse.ui.perspectiveExtensions" you could also add the view via code to the perspective. For this modify "Perspective.java" to the following.
package de.vogella.rcp.intro.view; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { layout.addView("de.vogella.rcp.intro.first.MyView", IPageLayout.TOP, IPageLayout.RATIO_MAX, IPageLayout.ID_EDITOR_AREA); } }

SWT is the UI library used by Eclipse. SWT provides the same rich UI components on several platforms using the native widgets of the platform whenever possible. If a widget is not available on a certain

32 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

framework via JNI.

Tutorials

Trainings

Books

Connect

For an introduction into SWT please use the SWT Tutorial.

JFace provides also viewers which allow to work with Java object directly to create an user interface. Viewers are available for trees, tables, lists and comboboxes. Please see JFaces Tables Tutorial and JFace Tree Viewer Tutorial for a detailed tutorial.

A command is a declarative description of a component and is independent from the implementation details. A command can be categorized and a hot key (key binding) can be assigned to it. Commands can be used in menus, toolbars and / or context menus. See Eclipse Commands Tutorial for an introduction into the commands framework.

Create a new RCP project called "de.vogella.rcp.intro.perspective". Use the "RCP application with a view" as a template. In "plugin.xml" add a new extension point "org.eclipse.ui.perspectives". Give the perspective with the id "de.vogella.rcp.intro.perspective.perspective" and the name "vogella.com Perspective". Change the class name to "de.vogella.rcp.intro.perspective.Perspective".

33 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Click on the "class*" link to create the class. The method createInitialLayout() in your new class is responsible for creating the new perspective. We re-use the existing view in the coding. After this step the perspective is defined but not yet reachable via the application.
package de.vogella.rcp.intro.perspective; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { String editorArea = layout.getEditorArea(); layout.setEditorAreaVisible(false); layout.setFixed(true); layout.addStandaloneView(View.ID, false, IPageLayout.LEFT, 1.0f, editorArea); } }

After defining your perspective you also need to enable your application so that the user can select this perspective. One alternative is to allow the user to select the perspective via the toolbar / coolbar. You can activate the switch between perspectives the ApplicationWorkbenchWindowAdvisor in method preWindowOpen() with configurer.setShowPerspectiveBar(true);
package de.vogella.rcp.intro.perspective;

34 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials
import import import import

Trainings

Books

Connect

org.eclipse.ui.application.ActionBarAdvisor; org.eclipse.ui.application.IActionBarConfigurer; org.eclipse.ui.application.IWorkbenchWindowConfigurer; org.eclipse.ui.application.WorkbenchWindowAdvisor;

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor { public ApplicationWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer) { super(configurer); } public ActionBarAdvisor createActionBarAdvisor( IActionBarConfigurer configurer) { return new ApplicationActionBarAdvisor(configurer); } public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); configurer.setInitialSize(new Point(400, 300)); configurer.setShowStatusLine(false); configurer.setTitle("RCP Application"); configurer.setShowPerspectiveBar(true); } }

You should now be able to select your perspective interactively.

35 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

allows to switch between perspectives. See Eclipse Commands.

Tutorials

Trainings

Books

Connect

The following add an icon for the RCP application to the system tray and adds a menu to this icon. We add the functionality that if the window is minimized then the program is not visible in the taskpane (only via the tray icon).

Create a new project "de.vogella.rcp.intro.traytest". Use the "Hello RCP" as a template. Open the class "ApplicationWorkbenchWindowAdvisor" and maintain the following code.
package de.vogella.rcp.intro.traytest; import import import import import import import import import import import import import import import import import import import org.eclipse.swt.SWT; org.eclipse.swt.events.MenuDetectEvent; org.eclipse.swt.events.MenuDetectListener; org.eclipse.swt.events.SelectionAdapter; org.eclipse.swt.events.SelectionEvent; org.eclipse.swt.events.ShellAdapter; org.eclipse.swt.events.ShellEvent; org.eclipse.swt.graphics.Image; org.eclipse.swt.graphics.Point; org.eclipse.swt.widgets.Menu; org.eclipse.swt.widgets.MenuItem; org.eclipse.swt.widgets.Shell; org.eclipse.swt.widgets.Tray; org.eclipse.swt.widgets.TrayItem; org.eclipse.ui.IWorkbenchWindow; org.eclipse.ui.application.ActionBarAdvisor; org.eclipse.ui.application.IActionBarConfigurer; org.eclipse.ui.application.IWorkbenchWindowConfigurer; org.eclipse.ui.application.WorkbenchWindowAdvisor;

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor { private IWorkbenchWindow window; private TrayItem trayItem; private Image trayImage; public ApplicationWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer) {

36 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

public ActionBarAdvisor createActionBarAdvisor( IActionBarConfigurer configurer) { return new ApplicationActionBarAdvisor(configurer); } public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); configurer.setInitialSize(new Point(400, 300)); configurer.setShowCoolBar(false); configurer.setShowStatusLine(false); configurer.setTitle("Hello RCP"); //$NON-NLS-1$ }

// As of here is the new stuff @Override


public void postWindowOpen() { super.postWindowOpen(); window = getWindowConfigurer().getWindow(); trayItem = initTaskItem(window);

// Some OS might not support tray items


if (trayItem != null) { minimizeBehavior();

// Create exit and about action on the icon


hookPopupMenu(); } }

// Add a listener to the shell


private void minimizeBehavior() { window.getShell().addShellListener(new ShellAdapter() {

// If the window is minimized hide the window


public void shellIconified(ShellEvent e) { window.getShell().setVisible(false); } });

// If user double-clicks on the tray icons the application will be // visible again
trayItem.addSelectionListener(new SelectionAdapter() {

@Override
public void widgetSelected(SelectionEvent e) { Shell shell = window.getShell(); if (!shell.isVisible()) { window.getShell().setMinimized(false); shell.setVisible(true); } } });

37 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

// We hook up on menu entry which allows to close the application


private void hookPopupMenu() { trayItem.addMenuDetectListener(new MenuDetectListener() {

@Override
public void menuDetected(MenuDetectEvent e) { Menu menu = new Menu(window.getShell(), SWT.POP_UP);

// Creates a new menu item that terminates the program


MenuItem exit = new MenuItem(menu, SWT.NONE); exit.setText("Goodbye!"); exit.addSelectionListener(new SelectionAdapter() {

@Override
public void widgetSelected(SelectionEvent e) { window.getWorkbench().close(); } });

// We need to make the menu visible


menu.setVisible(true); } }); }

// This methods create the tray item and return a reference


private TrayItem initTaskItem(IWorkbenchWindow window) { final Tray tray = window.getShell().getDisplay().getSystemTray(); TrayItem trayItem = new TrayItem(tray, SWT.NONE); trayImage = Activator.getImageDescriptor("/icons/alt_about.gif") .createImage(); trayItem.setImage(trayImage); trayItem.setToolTipText("TrayItem"); return trayItem; }

// We need to clean-up after ourself @Override


public void dispose() { if (trayImage != null) { trayImage.dispose(); } if (trayItem != null) { trayItem.dispose(); } } }

38 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

behavior. If the application is minimized it should not be visible in the taskbar but only in the system tray.

Tutorials

Trainings

Books

Connect

25.1. Developing against the Eclipse IDE


If you develop Eclipse plug-ins, you reuse components of the Eclipse Platform for example SWT or JFace. The question is: how can you control which version of a specific plug-in is used? Per default these plug-ins are sourced directly from your Eclipse IDE. This is not an ideal approach, as this makes you dependent on your version of the Eclipse IDE. This can lead to problems, if developers are using different versions of Eclipse. It also makes it difficult to upgrade these plug-ins for everyone at the same time. If you follow this approach you would also need to install every plug-in required for your product either in your workspace or in your Eclipse IDE. The last problem with this approach is that you might unintentionally add plug-ins from the Eclipse IDE to your product.

25.2. Defining your Target Platform


Via a Target Platform you define the set of plug-ins which are available for development. For example you define which version of the SWT and JFace plug-in is part of your target platform. This makes you independent from the Eclipse IDE you are using. Developers with different versions of Eclipse will compile their work against the same set of plug-ins. A Target Platform is defined via a ".target" file. This target file defines the list of plug-ins and features.

39 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

same basis for development.

Tutorials

Trainings

Books

Connect

The most effective way of defining your Target Platform is to use (Eclipse p2) update sites. These are the same type of update sites which you use if you want to install a new set of plug-ins. If the content in the update site defined by your target platform is changed, your local set of plug-ins can also be updated. It is also possible to define your target platform based on a file system, but this is not as flexible and therefore should be avoided.

25.3. Creating a Target Platform definition


A Target Definition file can be created via File New Other Plug-in Development Target Definition.

40 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

You can add new locations via the Add button in the location section. To add an Eclipse p2 update site, select "Software Site" and specify the URL. After you have defined your Target Definition file, you can set it as target in your Eclipse IDE via the "Set as Target Platform" button.

41 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

You can switch the target platform in the Eclipse Preferences. Select Window Preferences Plug-in Development Target Platform

42 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

To interact with the Workbench you have access to the Workbench API. For example you can access the

43 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Most API calls are done via the WorkbenchPage. A command handler can get access to the WorkbenchPage via:
IWorkbenchPage page = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();

A view provides access to the Workbench and the WorkbenchWindow via the getViewSite() method. An editor provides the same access via getEditorSite().
IWorkbenchPage page = getViewSite().getPage();

IWorkbenchPage page = getEditorSite().getPage();

You could also get the Workbench page over the PlatformUI Singleton.
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()

Once you have access to the Page you can call its API. The following demonstrates how to first close all views in the running application and how to open a View with a specific ID.
IViewReference[] views = page.getViewReferences(); for (IViewReference view : views) { page.hideView(view); } try { page.showView(View.ID); } catch (PartInitException e) { e.printStackTrace(); } return null;

The following shows how to save an editor and how to close it.

44 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

// Save the editor without confirmation


page.saveEditor(editorPart, false);

// Close the editor and save before saving


page.closeEditor(editorPart, true); }

You can also add a PartListener to the page and listen for change in View and Editors. Here is an example how to add such a listener in ApplicationWorkbenchWindowAdvisor.
@Override
public void postWindowOpen() { super.postWindowOpen(); IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage();

// Register a part listener for a certain View / Part


page.addPartListener(new IPartListener2() {

@Override
public void partVisible(IWorkbenchPartReference partRef) { System.out.println("Part visible: " + partRef.getId()); }

@Override
public void partOpened(IWorkbenchPartReference partRef) { System.out.println("Part opened: " + partRef.getId()); }

@Override
public void partInputChanged(IWorkbenchPartReference partRef) { }

@Override
public void partHidden(IWorkbenchPartReference partRef) { System.out.println("Part hidden: " + partRef.getId()); }

@Override
public void partDeactivated(IWorkbenchPartReference partRef) { System.out.println("Part deactivated:" + partRef.getId()); }

@Override
public void partClosed(IWorkbenchPartReference partRef) { System.out.println("Part closed:" + partRef.getId());

45 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books
@Override

Connect

public void partBroughtToTop(IWorkbenchPartReference partRef) { System.out.println("Part top:" + partRef.getId()); }

@Override
public void partActivated(IWorkbenchPartReference partRef) { System.out.println("Part activated: " + partRef.getId()); } }); }

27.1. Load an image from your plugin


To load an image from your plug-in your use the AbstractUIPlugin.
AbstractUIPlugin.imageDescriptorFromPlugin(YourPluginId,/icons/your.gif).createImage();

Alternatively you could load the framework directly.


Bundle bundle = FrameworkUtil.getBundle(this.getClass()); URL url = FileLocator.find(bundle, new Path("icons/alt_window_32.gif"), null); Image image = ImageDescriptor.createFromURL(url).createImage();

27.2. Save users layout


To remember the user's layout and window size for the next time you start your application, add configurer.setSaveAndRestore(true); to the initialize method of ApplicationWorkbenchAdvisor.
package addactiontoview; import import import import org.eclipse.ui.application.IWorkbenchConfigurer; org.eclipse.ui.application.IWorkbenchWindowConfigurer; org.eclipse.ui.application.WorkbenchAdvisor; org.eclipse.ui.application.WorkbenchWindowAdvisor;

46 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

private static final String PERSPECTIVE_ID = "AddActiontoView.perspective"; public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public String getInitialWindowPerspectiveId() { return PERSPECTIVE_ID; }

@Override
public void initialize(IWorkbenchConfigurer configurer) { super.initialize(configurer); configurer.setSaveAndRestore(true); } }

Eclipse has a pre-defined command to reset the perspective. See Eclipse Commands .

27.3. Accessing the status line


The status line in an RCP application can be used to give the user some information about the running application. The shared message area can be used by all parts of the application to write messages to this area. The whole RCP application has access to the information in the shared status line therefore the information in the shared status line might be overwritten. To show the status line in your RCP application use the "ApplicationWorkbenchWindowAdvisor" and set the status line visible in the method preWindowOpen().

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

//... @Override
public void preWindowOpen() {

// ....
configurer.setShowStatusLine(false); } }

47 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

The following writes a text to the status line from a view.

IStatusLineManager manager = getViewSite().getActionBars().getStatusLineManager(); manager.setMessage("Information for the status line");

From an editor you can access the status line via the following:
IEditorPart.getEditorSite().getActionBars();

27.4. Finding unused dependencies


In the file plugin.xml (tab dependencies) you define on which plugins your plugin depends. Of course you should only define the required plugins here. You can check if you have any dependency maintained which is actually not used, by selecting Dependency Analysis -> Find unused dependencies.

48 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

27.5. Multi-User settings


Eclipse RCP applications save configuration files in the folder ".metadata". In the standard settings the Eclipse RCP installation directory will be used for this folder. If several users are using the same installation folder, then you should supply the parameter "-data" to specify an alternative location. If you specify the value "@user.home/applicationname" the configuration will be saved in a user specific folder.

49 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

To access files in your bundle you can use you can use a Eclipse specific URL. The following shows an example how to access a file in the "files" folder of a specific plug-in.
URL url; try {

// de.vogella.rcp.plugin.filereader is the Bundle ID // files is the folder // test.txt is the file


url = new URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt"); InputStream inputStream = url.openConnection().getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); }

This requires that your plug-in has a dependency to org.eclipse.core.runtime defined.

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

30.1. Source Code


Source Code of Examples

50 of 51

17-05-2012 00:45

Eclipse RCP Tutorial

http://www.vogella.com/articles/EclipseRCP/article.html

Home

Tutorials

Trainings

Books

Connect

Using Eclipse IDE (Kindle Book) Eclipse Plug-in Development FAQ SWT Graphics

30.3. vogella Resources


Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel Android Tutorial Introduction to Android Programming GWT Tutorial Program in Java and compile to JavaScript and HTML Eclipse RCP Tutorial Create native applications in Java JUnit Tutorial Test your application Git Tutorial Put everything you have under distributed version control system

51 of 51

17-05-2012 00:45

Potrebbero piacerti anche